
    ijm                       U d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	m
Z
mZmZ ddlmZmZ ddlmZ ddlmZmZmZmZmZmZmZmZ ddlmZ ddlmZmZm Z m!Z!m"Z"m#Z# dd	l$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ dd
l,m-Z-m.Z.m/Z/ er)ddl0Z0ddl1m2Z2m3Z3m4Z4 ddl$m5Z5m6Z6m7Z7m8Z8m9Z9  ede:e7         Z;g dZ<ejz                  dk\  rddini Z> ej~                  dKddddde> G d dee)                Z@[> G d d      ZA eA       ZBdeCd<    e       ZDdeCd<   [Aer8ddlEmFZF  eFd      ZG ed      ZH eFd      ZI ed       ZJ G d! d"eeGeHeIeJf         ZK	 	 	 	 dLd#ZLed$d%	 	 	 	 	 dMd&       ZMe	 dNd$d%	 	 	 	 	 dOd'       ZM	 dNd$d%	 	 	 	 	 dPd(ZM eLeM      ed)	 	 	 	 	 	 	 	 	 	 	 dQd*       ZN[M[Le	 dNddd+	 	 	 	 	 	 	 dRd,       ZOe	 	 	 	 	 	 	 	 dSd-       ZO	 dNddd+	 	 	 	 	 	 	 dTd.ZOdUd/ZPej                  dVd0       ZRdWd1ZSdXd2ZTdYd3ZUdZd4ZVd[d5ZWd\d6ZXd]d7ZYd^d8ZZd_d9Z[	 	 	 	 d^d:Z\d_d;Z]	 	 	 	 d`d<Z^dad=Z_	 	 	 	 dbd>Z`	 	 	 	 	 	 dcd?Za	 	 	 	 dbd@Zb	 	 	 	 	 	 dcdAZcdddBZddedCZedfdDZfdgdEZgdhdFZh	 	 	 	 	 	 didGZi e:d       e@ e:d      eTeUe!e'j                  H      ek e@ekeVeWe"e'j                  H      em e@emeXeYe"e'j                  H      eo e@eoeZe[ee'j                  H      e e@eefege e'j                  H      e	 e@e	e^e_ee'j                  H      e
 e@e
e`eaee'j                  H      e e@eedeee"e'j                  H      e( e@e(eheie#e'j                  H      i	ZvdIeCdJ<    e@eoe\e]ee'j                  H      Zw e@e
ebecee'j                  H      Zxy)jz&Registry for custom pytree node types.    )annotationsN)OrderedDictdefaultdictdeque
namedtuple)
itemgettermethodcaller)Lock)TYPE_CHECKINGAnyCallableClassVarGeneric
NamedTupleTypeVaroverload)	AutoEntryMappingEntryNamedTupleEntryPyTreeEntrySequenceEntryStructSequenceEntry)ChildrenMetaData
PyTreeKindStructSequenceTis_namedtuple_classis_structseq_class)safe_ziptotal_order_sortedunzip2)
Collection	GeneratorIterable)KTVTCustomTreeNodeFlattenFuncUnflattenFuncCustomTreeNodeType)bound)register_pytree_noderegister_pytree_node_classunregister_pytree_nodedict_insertion_ordered   
   slotsT)initrepreqfrozenc                      e Zd ZU dZded<   ded<   ded<   ej                  dk\  rd	ed
<   eZded<   e	j                  Zded<   dZded<   y)PyTreeNodeRegistryEntryz>A dataclass that stores the information of a pytree node type.zbuiltins.type[Collection[T]]typeFlattenFunc[T]flatten_funcUnflattenFunc[T]unflatten_funcr1   zdataclasses.KW_ONLY_zbuiltins.type[PyTreeEntry]path_entry_typer   kind str	namespaceN)__name__
__module____qualname____doc____annotations__sysversion_infor   rA   r   CUSTOMrB   rE        d/var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/optree/registry.pyr:   r:   I   sP    H
&&  $$
7"2;O/;!((D*(IsrO   r:   c                  $    e Zd ZU dZded<   ddZy)GlobalNamespacerN   zClassVar[tuple[()]]	__slots__c                    y)Nz<GLOBAL NAMESPACE>rN   selfs    rP   __repr__zGlobalNamespace.__repr__`   s    #rO   N)returnrD   )rF   rG   rH   rS   rJ   rW   rN   rO   rP   rR   rR   ]   s    %'I"'$rO   rR   rD   __GLOBAL_NAMESPACEr
   __REGISTRY_LOCK)	ParamSpec_P_T_GetP_GetTc                      e Zd ZddZddZy)_CallableWithGetc                   t         NNotImplementedErrorrV   argskwargss      rP   __call__z_CallableWithGet.__call__r       %%rO   c                   t         rc   rd   rf   s      rP   getz_CallableWithGet.getv   rj   rO   N)rg   z_P.argsrh   z	_P.kwargsrX   r]   )rg   z
_GetP.argsrh   z_GetP.kwargsrX   r_   )rF   rG   rH   ri   rl   rN   rO   rP   ra   ra   q   s    	&	&rO   ra   c                    d fd}|S )Nc                   | _         | S rc   )rl   )funcrl   s    rP   	decoratorz_add_get.<locals>.decorator   s    rO   )ro   zCallable[_P, _T]rX   z&_CallableWithGet[_P, _T, _GetP, _GetT]rN   )rl   rp   s   ` rP   _add_getrq   z   s     rO   rC   )rE   c                   y rc   rN   clsrE   s     rP   pytree_node_registry_getru      s     &)rO   c                   y rc   rN   rs   s     rP   ru   ru      s     +.rO   c              J   |t         u rd}| ,| t        ur$t        j                  |       st	        d| d      t        |t              st	        d|d      | t        |dh      }t        5  t        j                         D ci c]  }|j                  |v r|j                  | }}ddd       t        j                  |      rt        t         <   t"        |t$        <   S |dk7  rt        j'                  || f      }||S t        j                  |      r| t         u rt        S | t$        u rt"        S t        j'                  |       }||S t)        |       rt        j'                  t*              S t-        |       rt        j'                  t              S yc c}w # 1 sw Y   xY w)a  Look up the pytree node registry.

    >>> register_pytree_node.get()  # doctest: +IGNORE_WHITESPACE,ELLIPSIS
    {
        <class 'NoneType'>: PyTreeNodeRegistryEntry(
            type=<class 'NoneType'>,
            flatten_func=<function ...>,
            unflatten_func=<function ...>,
            path_entry_type=<class 'optree.PyTreeEntry'>,
            kind=<PyTreeKind.NONE: 2>,
            namespace=''
        ),
        <class 'tuple'>: PyTreeNodeRegistryEntry(
            type=<class 'tuple'>,
            flatten_func=<function ...>,
            unflatten_func=<function ...>,
            path_entry_type=<class 'optree.SequenceEntry'>,
            kind=<PyTreeKind.TUPLE: 3>,
            namespace=''
        ),
        <class 'list'>: PyTreeNodeRegistryEntry(
            type=<class 'list'>,
            flatten_func=<function ...>,
            unflatten_func=<function ...>,
            path_entry_type=<class 'optree.SequenceEntry'>,
            kind=<PyTreeKind.LIST: 4>,
            namespace=''
        ),
        ...
    }
    >>> register_pytree_node.get(defaultdict)  # doctest: +IGNORE_WHITESPACE,ELLIPSIS
    PyTreeNodeRegistryEntry(
        type=<class 'collections.defaultdict'>,
        flatten_func=<function ...>,
        unflatten_func=<function ...>,
        path_entry_type=<class 'optree.MappingEntry'>,
        kind=<PyTreeKind.DEFAULTDICT: 8>,
        namespace=''
    )
    >>> register_pytree_node.get(frozenset)  # frozenset is considered as a leaf node
    None

    Args:
        cls (type or None, optional): The class of the pytree node to retrieve. If not provided, all
            the registered pytree nodes in the namespace are returned.
        namespace (str, optional): The namespace of the registry to retrieve. If not provided, the
            global namespace is used.

    Returns:
        If the ``cls`` is not provided, a dictionary of all the registered pytree nodes in the
        namespace is returned. If the ``cls`` is provided, the corresponding registry entry is
        returned if the ``cls`` is registered as a pytree node. Otherwise, :data:`None` is returned,
        i.e., the ``cls`` is represented as a leaf node.
    rC   NzExpected a class or None, got .$The namespace must be a string, got )rY   r   inspectisclass	TypeError
isinstancerD   	frozensetrZ   _NODETYPE_REGISTRYvaluesrE   r;   _Cis_dict_insertion_ordered&_DICT_INSERTION_ORDERED_REGISTRY_ENTRYdict-_DEFAULTDICT_INSERTION_ORDERED_REGISTRY_ENTRYr   rl   r   r   r   )rt   rE   
namespaceshandlerregistrys        rP   ru   ru      s   x &&	z!$8qABBi%29-qA
 	
 {	2/
 	  288:$$
2 g%H 	 ''	2CHTN$QH[!B$(()S)9:N	##I.$;99+@@ $$S)G#!%%n553!%%j119	 	s   -F"F&FFF")rA   c                 t        j                  |       st        d| d      t        j                  |      rt        |t              st        d|d      |t
        urt        |t              st        d|d      |dk(  rt        d      |t
        u r| }d}n|| f}t        5  t        j                  | ||||       t        | ||||      t        |<   ddd       | S # 1 sw Y   | S xY w)	a3  Extend the set of types that are considered internal nodes in pytrees.

    See also :func:`register_pytree_node_class` and :func:`unregister_pytree_node`.

    The ``namespace`` argument is used to avoid collisions that occur when different libraries
    register the same Python type with different behaviors. It is recommended to add a unique prefix
    to the namespace to avoid conflicts with other libraries. Namespaces can also be used to specify
    the same class in different namespaces for different use cases.

    .. warning::
        For safety reasons, a ``namespace`` must be specified while registering a custom type. It is
        used to isolate the behavior of flattening and unflattening a pytree node type. This is to
        prevent accidental collisions between different libraries that may register the same type.

    Args:
        cls (type): A Python type to treat as an internal pytree node.
        flatten_func (callable): A function to be used during flattening, taking an instance of ``cls``
            and returning a triple or optionally a pair, with (1) an iterable for the children to be
            flattened recursively, and (2) some hashable metadata to be stored in the treespec and
            to be passed to the ``unflatten_func``, and (3) (optional) an iterable for the tree path
            entries to the corresponding children. If the entries are not provided or given by
            :data:`None`, then `range(len(children))` will be used.
        unflatten_func (callable): A function taking two arguments: the metadata that was returned
            by ``flatten_func`` and stored in the treespec, and the unflattened children. The
            function should return an instance of ``cls``.
        path_entry_type (type, optional): The type of the path entry to be used in the treespec.
            (default: :class:`AutoEntry`)
        namespace (str): A non-empty string that uniquely identifies the namespace of the type registry.
            This is used to isolate the registry from other modules that might register a different
            custom behavior for the same type.

    Returns:
        The same type as the input ``cls``.

    Raises:
        TypeError: If the input type is not a class.
        TypeError: If the path entry class is not a subclass of :class:`PyTreeEntry`.
        TypeError: If the namespace is not a string.
        ValueError: If the namespace is an empty string.
        ValueError: If the type is already registered in the registry.

    .. versionadded:: 0.12.0
        The ``path_entry_type`` argument to specify the path entry type used in
        :meth:`PyTreeSpec.accessors` and :func:`tree_flatten_with_accessor`.
        If not provided, :class:`AutoEntry` will be used.

    Examples:
        >>> # Register a Python type with lambda functions
        >>> register_pytree_node(
        ...     set,
        ...     lambda s: (sorted(s), None, None),
        ...     lambda _, children: set(children),
        ...     namespace='set',
        ... )
        <class 'set'>

        >>> # Register a custom type into a namespace with accessor support
        >>> import types
        >>> # This can be whatever your container type is.
        >>> class MyContainer(types.SimpleNamespace):
        ...     pass
        >>> # (Optional) Define a custom path entry type for accessor support.
        >>> # Here we showcase how to define one. In practice, you can use the built-in ``GetAttrEntry``.
        >>> class MyContainerEntry(PyTreeEntry):
        ...     def __call__(self, obj):
        ...         return getattr(obj, self.entry)
        ...     def codify(self, node=''):
        ...         return f'{node}.{self.entry}'
        >>> register_pytree_node(  # doctest: +ELLIPSIS
        ...     MyContainer,
        ...     flatten_func=lambda ct: (
        ...         list(vars(ct).values()),
        ...         list(vars(ct).keys()),
        ...         list(vars(ct).keys()),
        ...     ),
        ...     unflatten_func=lambda keys, values: MyContainer(**dict(zip(keys, values))),
        ...     path_entry_type=MyContainerEntry,
        ...     namespace='mycontainer',
        ... )
        <class '...MyContainer'>

        >>> tree = {'config': MyContainer(lr=0.01, momentum=0.9), 'steps': 1000}

        >>> # Flatten without specifying the namespace
        >>> tree_flatten(tree)  # `MyContainer`s are leaf nodes
        ([MyContainer(lr=0.01, momentum=0.9), 1000], PyTreeSpec({'config': *, 'steps': *}))

        >>> # Flatten with the namespace
        >>> leaves, treespec = tree_flatten(tree, namespace='mycontainer')
        >>> leaves, treespec
        ([0.01, 0.9, 1000], PyTreeSpec({'config': CustomTreeNode(MyContainer[['lr', 'momentum']], [*, *]), 'steps': *}, namespace='mycontainer'))

        >>> # Custom ``entries`` are defined as attribute names
        >>> tree_paths(tree, namespace='mycontainer')
        [('config', 'lr'), ('config', 'momentum'), ('steps',)]

        >>> # Custom path entry type defines the pytree access behavior
        >>> accessors = tree_accessors(tree, namespace='mycontainer')
        >>> accessors[0].codify()
        "*['config'].lr"
        >>> accessors[0](tree)
        0.01

        >>> # Unflatten back to a copy of the original object
        >>> tree_unflatten(treespec, leaves)
        {'config': MyContainer(lr=0.01, momentum=0.9), 'steps': 1000}
    Expected a class, got rx   (Expected a subclass of PyTreeEntry, got ry   rC   (The namespace cannot be an empty string.rA   rE   N)rz   r{   r|   
issubclassr   rY   r}   rD   
ValueErrorrZ   r   register_noder:   r   )rt   r=   r?   rA   rE   registration_keys         rP   r-   r-     s   j ??30q9::OOO,O[1YB?BUUVWXX**:i3M>ym1MNNBCDD &&	%s+	 

	
 0G+0
+,
 J
 Js   '1C""C,r   c                   y rc   rN   rt   rA   rE   s      rP   r.   r.     s     :=rO   c                   y rc   rN   r   s      rP   r.   r.     s     rO   c                   t         u st         t              r"t        d       dk(  rt        d      d c t        d      t         urt        t              st	        d      dk(  rt        d       	dfd}|S t        j                         st	        d d	      t         d
t              t        j                        rt        t              st	        dd	      t         fddD              st         fddD              st	         d      t        j                   j                        	 	 	 	 dd       }t        t        j                  t         j                   d j                               	 	 	 	 	 	 	 	 dd              }| _        | _        t'         t)        d       j$                          S )a  Extend the set of types that are considered internal nodes in pytrees.

    See also :func:`register_pytree_node` and :func:`unregister_pytree_node`.

    The ``namespace`` argument is used to avoid collisions that occur when different libraries
    register the same Python type with different behaviors. It is recommended to add a unique prefix
    to the namespace to avoid conflicts with other libraries. Namespaces can also be used to specify
    the same class in different namespaces for different use cases.

    .. warning::
        For safety reasons, a ``namespace`` must be specified while registering a custom type. It is
        used to isolate the behavior of flattening and unflattening a pytree node type. This is to
        prevent accidental collisions between different libraries that may register the same type.

    Args:
        cls (type, optional): A Python type to treat as an internal pytree node.
        path_entry_type (type, optional): The type of the path entry to be used in the treespec.
            (default: :class:`AutoEntry`)
        namespace (str, optional): A non-empty string that uniquely identifies the namespace of the
            type registry. This is used to isolate the registry from other modules that might
            register a different custom behavior for the same type.

    Returns:
        The same type as the input ``cls`` if the argument presents. Otherwise, return a decorator
        function that registers the class as a pytree node.

    Raises:
        TypeError: If the path entry class is not a subclass of :class:`PyTreeEntry`.
        TypeError: If the namespace is not a string.
        TypeError: If the class does not define the required method pairs.
        ValueError: If the namespace is an empty string.
        ValueError: If the type is already registered in the registry.

    .. versionadded:: 0.12.0
        The ``TREE_PATH_ENTRY_TYPE`` class variable to specify the path entry type used in
        :meth:`PyTreeSpec.accessors` and :func:`tree_flatten_with_accessor`.
        If not provided, :class:`AutoEntry` will be used.

    .. versionadded:: 0.18.0
        Previously, this function looked for methods named ``tree_flatten`` and ``tree_unflatten``
        for the given class. Since version 0.18.0, it prefers methods named ``__tree_flatten__``
        and ``__tree_unflatten__`` instead. The old method names are still supported for
        backward compatibility, but it is recommended to use the new method names.
        The method resolution follows this priority:
        1. If both ``__tree_flatten__`` and ``__tree_unflatten__`` are defined, use them directly.
        2. If both ``tree_flatten`` and ``tree_unflatten`` are defined, wrap them as dunder methods.
        3. If neither complete pair is available, raise a :exc:`TypeError` suggesting the new method names.

    This function is a thin wrapper around :func:`register_pytree_node`, and provides a
    class-oriented interface:

    .. code-block:: python

        @register_pytree_node_class(namespace='foo')
        class Special:
            TREE_PATH_ENTRY_TYPE = GetAttrEntry

            def __init__(self, x, y):
                self.x = x
                self.y = y

            def __tree_flatten__(self):
                return ((self.x, self.y), None, ('x', 'y'))

            @classmethod
            def __tree_unflatten__(cls, metadata, children):
                return cls(*children)

        @register_pytree_node_class('mylist')
        class MyList(UserList):
            TREE_PATH_ENTRY_TYPE = SequenceEntry

            def __tree_flatten__(self):
                return self.data, None, None

            @classmethod
            def __tree_unflatten__(cls, metadata, children):
                return cls(*children)

        # Legacy style (still supported but not recommended)
        @register_pytree_node_class(namespace='legacy')
        class LegacyStyleMyList(UserList):
            def tree_flatten(self):
                # Implementation automatically wrapped as __tree_flatten__
                return self.data, None, None

            @classmethod
            def tree_unflatten(cls, metadata, children):
                # Implementation automatically wrapped as __tree_unflatten__
                return cls(*children)
    Nz?Cannot specify `namespace` when the first argument is a string.rC   r   z<Must specify `namespace` when the first argument is a class.ry   c                    t        |       S )Nr   )r.   )rt   rE   rA   s    rP   rp   z-register_pytree_node_class.<locals>.decorator'  s    - /# rO   r   rx   TREE_PATH_ENTRY_TYPEr   c              3  J   K   | ]  }t        t        |d               y wrc   callablegetattr.0methodrt   s     rP   	<genexpr>z-register_pytree_node_class.<locals>.<genexpr>8  s'       	fd+,    #)__tree_flatten____tree_unflatten__c              3  J   K   | ]  }t        t        |d               y wrc   r   r   s     rP   r   z-register_pytree_node_class.<locals>.<genexpr>=  s$      
5;HWS&$/0
r   )tree_flattentree_unflattenzh must define both `__tree_flatten__` and `__tree_unflatten__` methods for registration as a pytree node.c               "    | j                         S rc   )r   rU   s    rP   r   z4register_pytree_node_class.<locals>.__tree_flatten__H  s    
 $$&&rO   __func__c               &    | j                  ||      S rc   )r   )rt   metadatachildrens      rP   r   z6register_pytree_node_class.<locals>.__tree_unflatten__O  s     %%h99rO   r   r   )rt   r+   rX   r+   )rV   CustomTreeNode[T]rX   zQtuple[Children[T], MetaData] | tuple[Children[T], MetaData, Iterable[Any] | None])rt   ztype[CustomTreeNode[T]]r   r   r   zChildren[T]rX   r   )rY   r}   rD   r   r|   rz   r{   r   r   r   r   all	functoolswrapsr   classmethodr   r   r   r-   r	   )rt   rA   rE   rp   r   r   s   ```   rP   r.   r.     s#   D   JsC$8 ^__"9GHHsYWXX**:i3M>ymLMMBCDD
{	 ??30q9::!#'=yIOOO,O[1YB?BUUVWXX  @ 
  
?a
 
 ' 5 5  
))	*	'#	' _	' 
+	' 
	!3!3ZASAST	U	:(	:	: "	:
 	: 
V 
	:  0!3'(' JrO   c              h   t        j                  |       st        d| d      |t        urt	        |t
              st        d|d      |dk(  rt        d      |t        u r| }d}n|| f}t        5  t        j                  | |       t        j                  |      cddd       S # 1 sw Y   yxY w)a  Remove a type from the pytree node registry.

    See also :func:`register_pytree_node` and :func:`register_pytree_node_class`.

    This function is the inverse operation of function :func:`register_pytree_node`.

    Args:
        cls (type): A Python type to remove from the pytree node registry.
        namespace (str): The namespace of the pytree node registry to remove the type from.

    Returns:
        The removed registry entry.

    Raises:
        TypeError: If the input type is not a class.
        TypeError: If the namespace is not a string.
        ValueError: If the namespace is an empty string.
        ValueError: If the type is a built-in type that cannot be unregistered.
        ValueError: If the type is not found in the registry.

    Examples:
        >>> # Register a Python type with lambda functions
        >>> register_pytree_node(
        ...     set,
        ...     lambda s: (sorted(s), None, None),
        ...     lambda _, children: set(children),
        ...     namespace='temp',
        ... )
        <class 'set'>

        >>> # Unregister the Python type
        >>> unregister_pytree_node(set, namespace='temp')
    r   rx   ry   rC   r   N)rz   r{   r|   rY   r}   rD   r   rZ   r   unregister_noder   pop)rt   rE   r   s      rP   r/   r/   h  s    D ??30q9::**:i3M>ym1MNNBCDD &&	%s+	 8
3	*!%%&678 8 8s   3+B((B1c            #    K   |t         urt        |t              st        d|d      |dk(  rt	        d      |t         u rd}t
        5  t        j                  |d      }t        j                  t        |       |       ddd       	 d t
        5  t        j                  |       ddd       y# 1 sw Y   4xY w# 1 sw Y   yxY w# t
        5  t        j                  |       ddd       w # 1 sw Y   w xY wxY ww)a  Context manager to temporarily set the dictionary sorting mode.

    This context manager is used to temporarily set the dictionary sorting mode for a specific
    namespace. The dictionary sorting mode is used to determine whether the keys of a dictionary
    should be sorted or keep the insertion order when flattening a pytree.

    >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5}
    >>> tree_flatten(tree)  # doctest: +IGNORE_WHITESPACE
    (
        [1, 2, 3, 4, 5],
        PyTreeSpec({'a': *, 'b': (*, [*, *]), 'c': None, 'd': *})
    )
    >>> with dict_insertion_ordered(True, namespace='some-namespace'):  # doctest: +IGNORE_WHITESPACE
    ...     tree_flatten(tree, namespace='some-namespace')
    (
        [2, 3, 4, 1, 5],
        PyTreeSpec({'b': (*, [*, *]), 'a': *, 'c': None, 'd': *}, namespace='some-namespace')
    )

    .. warning::
        The dictionary sorting mode is a global setting and is **not thread-safe**. It is
        recommended to use this context manager in a single-threaded environment.

    Args:
        mode (bool): The dictionary sorting mode to set.
        namespace (str): The namespace to set the dictionary sorting mode for.
    ry   rx   rC   r   F)inherit_global_namespaceN)
rY   r}   rD   r|   r   rZ   r   r   set_dict_insertion_orderedbool)moderE   prevs      rP   r0   r0     s     : **:i3M>ym1MNNBCDD&&		 =++IPUV
%%d4j)<=; 	;))$	:	; 	;= =	; 	;_ 	;))$	:	; 	; 	;sf   AD
7B4D
C DC +	D4B=9D C	DC?C3*	C?3C<8C??Dc               .    t        | t        d            S )Nr   )key)r!   r   )itemss    rP   _sorted_itemsr     s    eA77rO   c                    y)N)rN   NrN   )r@   s    rP   _none_flattenr     s    rO   c               \    t               }t        t        |      |      |urt        d      y )NzExpected no children.)objectnextiterr   )r@   r   sentinels      rP   _none_unflattenr     s-    xHDNH%X5011 6rO   c               
    | d fS rc   rN   tups    rP   _tuple_flattenr         9rO   c                   t        |      S rc   )tupler@   r   s     rP   _tuple_unflattenr     s    ?rO   c               
    | d fS rc   rN   )lsts    rP   _list_flattenr     r   rO   c                   t        |      S rc   )listr   s     rP   _list_unflattenr     s    >rO   c               h    t        t        | j                                     \  }}|t        |      |fS rc   )r"   r   r   r   dctkeysr   s      rP   _dict_flattenr     s,    -		45LD&4:t##rO   c               ,    t        t        | |            S rc   r   r    r   r   s     rP   _dict_unflattenr         v&''rO   c               V    t        | j                               \  }}|t        |      |fS rc   r"   r   r   r   s      rP   _dict_insertion_ordered_flattenr     )     #))+&LD&4:t##rO   c               ,    t        t        | |            S rc   r   r   s     rP   !_dict_insertion_ordered_unflattenr     r   rO   c               V    t        | j                               \  }}|t        |      |fS rc   r   r   s      rP   _ordereddict_flattenr     r   rO   c               ,    t        t        | |            S rc   )r   r    r   s     rP   _ordereddict_unflattenr     s    xf-..rO   c               B    t        |       \  }}}|| j                  |f|fS rc   )r   default_factoryr   r   dict_metadataentriess       rP   _defaultdict_flattenr     s-     &33%7"FM7C''7@@rO   c               8    | \  }}t        |t        ||            S rc   )r   r   r   r   r   r   s       rP   _defaultdict_unflattenr     s"    
 &."O]v(NOOrO   c               B    t        |       \  }}}|| j                  |f|fS rc   )r   r   r   s       rP   &_defaultdict_insertion_ordered_flattenr   (  s.     &ES%I"FM7C''7@@rO   c               8    | \  }}t        |t        ||            S rc   )r   r   r   s       rP   (_defaultdict_insertion_ordered_unflattenr   4  s$    
 &."O](I-Y_(`aarO   c                   | | j                   fS rc   maxlen)deqs    rP   _deque_flattenr   =  s    

?rO   c                   t        ||       S )Nr   )r   )r   r   s     rP   _deque_unflattenr   A  s    &))rO   c                   | t        |       fS rc   r;   r   s    rP   _namedtuple_flattenr   E      S	>rO   c                    | | S rc   rN   rt   r   s     rP   _namedtuple_unflattenr  J  s    >rO   c                   | t        |       fS rc   r   )seqs    rP   _structseq_flattenr  N  r   rO   c                    | |      S rc   rN   r  s     rP   _structseq_unflattenr  R  s    
 x=rO   )rA   rB   z6dict[type | tuple[str, type], PyTreeNodeRegistryEntry]r   rN   )rl   zCallable[_GetP, _GetT]rX   zDCallable[[Callable[_P, _T]], _CallableWithGet[_P, _T, _GetP, _GetT]])rt   r;   rE   rD   rX   zPyTreeNodeRegistryEntry | Nonerc   )rt   NonerE   rD   rX   z#dict[type, PyTreeNodeRegistryEntry])rt   ztype | NonerE   rD   rX   zDdict[type, PyTreeNodeRegistryEntry] | PyTreeNodeRegistryEntry | None)r=   r<   r?   r>   rt   type[Collection[T]]rA   ztype[PyTreeEntry]rE   rD   rX   r	  )rt   
str | NonerA   type[PyTreeEntry] | NonerE   r
  rX   z2Callable[[CustomTreeNodeType], CustomTreeNodeType])rt   r+   rA   r  rE   rD   rX   r+   )rt   zCustomTreeNodeType | str | NonerA   r  rE   r
  rX   zGCustomTreeNodeType | Callable[[CustomTreeNodeType], CustomTreeNodeType])rt   r;   rE   rD   rX   r:   )r   r   rE   rD   rX   zGenerator[None])r   zIterable[tuple[KT, VT]]rX   zlist[tuple[KT, VT]])r@   r  rX   ztuple[tuple[()], None])r@   r  r   zIterable[Any]rX   r  )r   tuple[T, ...]rX   ztuple[tuple[T, ...], None])r@   r  r   Iterable[T]rX   r  )r   list[T]rX   ztuple[list[T], None])r@   r  r   r  rX   r  )r   dict[KT, VT]rX   /tuple[tuple[VT, ...], list[KT], tuple[KT, ...]])r   list[KT]r   Iterable[VT]rX   r  )r   OrderedDict[KT, VT]rX   r  )r   r  r   r  rX   r  )r   defaultdict[KT, VT]rX   zOtuple[tuple[VT, ...], tuple[Callable[[], VT] | None, list[KT]], tuple[KT, ...]])r   z!tuple[Callable[[], VT], list[KT]]r   r  rX   r  )r   deque[T]rX   ztuple[deque[T], int | None])r   z
int | Noner   r  rX   r  )r   NamedTuple[T]rX   z)tuple[tuple[T, ...], type[NamedTuple[T]]])rt   ztype[NamedTuple[T]]r   r  rX   r  )r  StructSequence[T]rX   z-tuple[tuple[T, ...], type[StructSequence[T]]])rt   ztype[StructSequence[T]]r   r  rX   r  )yrI   
__future__r   
contextlibdataclassesr   rz   rK   collectionsr   r   r   r   operatorr   r	   	threadingr
   typingr   r   r   r   r   r   r   r   	optree._Cr   optree.accessorsr   r   r   r   r   r   optree.typingr   r   r   r   r   r   r   optree.utilsr    r!   r"   builtinscollections.abcr#   r$   r%   r&   r'   r(   r)   r*   r;   r+   __all__rL   SLOTS	dataclassr:   rR   rY   rJ   rZ   typing_extensionsr[   r\   r]   r^   r_   ra   rq   ru   r-   r.   r/   contextmanagerr0   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  NONEr   TUPLEr   LISTr   DICT
NAMEDTUPLEORDEREDDICTDEFAULTDICTDEQUESTRUCTSEQUENCEr   r   r   rN   rO   rP   <module>r3     s	   - #     
 C C -  a a a     > = ??PP !!5T.=QR ++w6$B KDtTKUKgaj  L 
$ $ *+ C +  +	4B	BgEGE&72r5%#78 &	 

 	)	) 	)
 $) 
) 
. 	.	. 	.
 ). 
. h 	h	h 	h
 JhV 

"# *3S !S %	S	S 'S S S $Sl h 
= 15 =	= .	=
 = 8= 
= 
	 .	
   
 ,0p 15 p	(p .	p
 p Mpf28j +; +;\82$
(	$		$	$(	$		$	$/	A		A	AP/PP 	P	A		A	Ab/bb 	b*
	  	 	J'T
#__ 
"% 	
!%__ 	
!$__ ''"" ($## ($## 
"% ++&&s@N J @F *A#% 	* & 1H*, 			1 -rO   