
    0VhN                    V   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Zddl ddl	m
Z
mZmZmZmZmZmZ ddlmZ e
rddlmZ g ej*                  ZdZd	Zd
ed<    ed      Z ed      Z ede      Zed	d	dd	dej:                  ddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d!d       Zed	d	dd	dej:                  ddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d"d       Zed	d	dd	dej:                  ddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d#d       Zej:                  ej:                  d	d	dd	dej:                  ddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d$dZed	d	d	dddd	dddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d%d       Zed	d	d	dddd	dddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d&d       Z eef      	 d'd	d	d	dddd	dddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d(d       Z G d dee         Z ddd	d	d	dddd	ddddej>                  d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d)d Z!y)*a  PyTree integration with :mod:`dataclasses`.

This module implements PyTree integration with :mod:`dataclasses` by redefining the :func:`field`,
:func:`dataclass`, and :func:`make_dataclass` functions. Other APIs are re-exported from the
original :mod:`dataclasses` module.

The PyTree integration allows dataclasses to be flattened and unflattened recursively. The fields
are stored in a special attribute named ``__optree_dataclass_fields__`` in the dataclass.

>>> import math
... import optree
...
>>> @optree.dataclasses.dataclass(namespace='my_module')
... class Point:
...     x: float
...     y: float
...     z: float = 0.0
...     norm: float = optree.dataclasses.field(init=False, pytree_node=False)
...
...     def __post_init__(self) -> None:
...         self.norm = math.hypot(self.x, self.y, self.z)
...
>>> point = Point(2.0, 6.0, 3.0)
>>> point
Point(x=2.0, y=6.0, z=3.0, norm=7.0)
>>> # Flatten without specifying the namespace
>>> optree.tree_flatten(point)  # `Point`s are leaf nodes
([Point(x=2.0, y=6.0, z=3.0, norm=7.0)], PyTreeSpec(*))
>>> # Flatten with the namespace
>>> accessors, leaves, treespec = optree.tree_flatten_with_accessor(point, namespace='my_module')
>>> accessors, leaves, treespec  # doctest: +IGNORE_WHITESPACE,ELLIPSIS
(
    [
        PyTreeAccessor(*.x, (DataclassEntry(field='x', type=<class '...Point'>),)),
        PyTreeAccessor(*.y, (DataclassEntry(field='y', type=<class '...Point'>),)),
        PyTreeAccessor(*.z, (DataclassEntry(field='z', type=<class '...Point'>),))
    ],
    [2.0, 6.0, 3.0],
    PyTreeSpec(CustomTreeNode(Point[()], [*, *, *]), namespace='my_module')
)
>>> point == optree.tree_unflatten(treespec, leaves)
True
    )annotationsN)*)TYPE_CHECKINGAnyCallableLiteralProtocolTypeVaroverload)dataclass_transform)Iterable__optree_dataclass_fields__Tbool_PYTREE_NODE_DEFAULT_T_U_TypeT)boundinitreprhashcomparemetadatakw_onlydocpytree_nodec        	             y N )	defaultr   r   r   r   r   r   r   r   s	            B/home/dcms/DCMS/lib/python3.12/site-packages/optree/dataclasses.pyfieldr#   \        
    c        	             y r   r    )	default_factoryr   r   r   r   r   r   r   r   s	            r"   r#   r#   k   r$   r%   c                     y r   r    r   s           r"   r#   r#   z   s     r%   )
r!   r'   r   r   r   r   r   r   r   r   c        
           |xs i j                         }|	|j                  dt              }	|	|d<   | ||||||d}
t        j                  dk\  r||
d<   n|t
        j                  urt        d      t        j                  dk\  r||
d<   n|t        d      |s|	rt        d	t         d
      t        j                  di |
S )a*  Field factory for :func:`dataclass`.

    This factory function is used to define the fields in a dataclass. It is similar to the field
    factory :func:`dataclasses.field`, but with an additional ``pytree_node`` parameter. If
    ``pytree_node`` is :data:`True` (default), the field will be considered a child node in the
    PyTree structure which can be recursively flattened and unflattened. Otherwise, the field will
    be considered as PyTree metadata.

    Setting ``pytree_node`` in the field factory is equivalent to setting a key ``'pytree_node'`` in
    ``metadata`` in the original field factory. The ``pytree_node`` value can be accessed using
    ``field.metadata['pytree_node']``. If ``pytree_node`` is :data:`None`, the value
    ``metadata.get('pytree_node', True)`` will be used.

    .. note::
        If a field is considered a child node, it must be included in the argument list of the
        :meth:`__init__` method, i.e., passes ``init=True`` in the field factory.

    Args:
        pytree_node (bool or None, optional): Whether the field is a PyTree node.
        **kwargs (optional): Optional keyword arguments passed to :func:`dataclasses.field`.

    Returns:
        dataclasses.Field: The field defined using the provided arguments with
        ``field.metadata['pytree_node']`` set.
    r   )r!   r'   r   r   r   r   r      
   r   z4field() got an unexpected keyword argument 'kw_only'r+      r   z0field() got an unexpected keyword argument 'doc'zN`pytree_node=True` is not allowed for non-init fields. Please explicitly set `'.field(init=False, pytree_node=False)`.r    )
copygetr   sysversion_infodataclassesMISSING	TypeError__name__r#   )r!   r'   r   r   r   r   r   r   r   r   kwargss              r"   r#   r#      s    L B$$&Hll=2FG)H] *F 7"#y	++	+NOO
7"u	JKKK&&.Z/VX
 	

 &v&&r%   F
r   r   eqorderunsafe_hashfrozen
match_argsr   slotsweakref_slotc                     y r   r    )r   r   r:   r;   r<   r=   r>   r   r?   r@   	namespaces              r"   	dataclassrC      s     "%r%   c                   y r   r    )clsr   r   r:   r;   r<   r=   r>   r   r?   r@   rB   s               r"   rC   rC      s      r%   )field_specifiersc              |    ddl m} ||||||dt        j                  dk\  r|d<   |d<   |	d<   n-|durt	        d	      |d
urt	        d      |	d
urt	        d      t        j                  dk\  r|
d<   n|
d
urt	        d       	d!fd}|S t        j                         st	        dt         d d      t         j                  v r t	        dt         d j                   d      |urt        t              st	        dd      dk(  r|t        j                   fi  i }i t        j                         D ]z  }|j                  j!                  dt"              r<|j$                  s t	        d|j&                  dt         d      |||j&                  <   _|j$                  sl||j&                  <   | t)        |      t+        j,                  |      }t+        j,                        t/         t        |f       	 	 	 	 d"fd}d# fd}ddlm} ddl m}  | |||       S )$a  Dataclass decorator with PyTree integration.

    Args:
        cls (type or None, optional): The class to decorate. If :data:`None`, return a decorator.
        namespace (str): The registry namespace used for the PyTree registration.
        **kwargs (optional): Optional keyword arguments passed to :func:`dataclasses.dataclass`.

    Returns:
        type or callable: The decorated class with PyTree integration or decorator function.
    r   __GLOBAL_NAMESPACEr   r   r:   r;   r<   r=   r*   r>   r   r?   Tz;dataclass() got an unexpected keyword argument 'match_args'Fz8dataclass() got an unexpected keyword argument 'kw_only'z6dataclass() got an unexpected keyword argument 'slots'r+      r@   z=dataclass() got an unexpected keyword argument 'weakref_slot'c                     t        | fdiS )NrB   )rC   )rE   r8   rB   s    r"   	decoratorzdataclass.<locals>.decorator-  s    S@I@@@r%   @z0.dataclass() can only be used with classes, not .z".dataclass() cannot be applied to z more than once.$The namespace must be a string, got  r   zPyTree node field z> must be included in `__init__()`. Or you can explicitly set `r/   c               `     t         fdD              }t         fdD              }||fS )Nc              3  6   K   | ]  }t        |        y wr   getattr.0nameobjs     r"   	<genexpr>z2dataclass.<locals>.flatten_func.<locals>.<genexpr>Y  s     Md+Ms   c              3  :   K   | ]  }|t        |      f  y wr   rU   rW   s     r"   r[   z2dataclass.<locals>.flatten_func.<locals>.<genexpr>Z  s     P$T 23Ps   )tuple)rZ   childrenr   children_field_namesmetadata_fieldss   `  r"   flatten_funczdataclass.<locals>.flatten_funcQ  s4     M8LMMPPP#777r%   c               `    t        t        |            }|j                  |         di |S )Nr    )dictzipupdate)r   r^   r8   r_   rE   s      r"   unflatten_funcz!dataclass.<locals>.unflatten_func^  s-    c.9:h}V}r%   )DataclassEntry)register_pytree_node)path_entry_typerB   )rE   r   returnr   )rZ   r   rj   zCtuple[tuple[_U, ...], tuple[tuple[str, Any], ...], tuple[str, ...]])r   ztuple[tuple[str, Any], ...]r^   ztuple[_U, ...]rj   r   )optree.registryrI   r2   r3   r6   inspectisclassr7   _FIELDS__dict__
isinstancestrr4   rC   fieldsr   r1   r   r   rY   r]   typesMappingProxyTypesetattroptree.accessorsrg   rh   )rE   r   r   r:   r;   r<   r=   r>   r   r?   r@   rB   GLOBAL_NAMESPACErN   children_fieldsfra   rf   rg   rh   r_   r8   r`   s   `          `        @@@r"   rC   rC      s}   8 G "F 7")|#yw	4	UVV		RSS	e	PQQ
7"!-~	U	"WXX
{	A ??3!H:%UVYU\\]^__#,,z;CLL>IYZ
 	
 ((Is1K>ym1MNNB$	



.v
.COO$ 	(::>>-)=>66(
 322:;bd  '(OAFF#VV&'OAFF#	( !1,,_=O,,_=OC?O<=
8
8

8
 04& r%   c                  Z    e Zd Zddddddddddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy)_DataclassDecoratorTFr9   c      
            t         r   )NotImplementedError)selfrE   r   r   r:   r;   r<   r=   r>   r   r?   r@   s               r"   __call__z_DataclassDecorator.__call__p  s
      "!r%   N)rE   r   r   r   r   r   r:   r   r;   r   r<   r   r=   r   r>   r   r   r   r?   r   r@   r   rj   r   )r7   
__module____qualname__r   r    r%   r"   r{   r{   o  s     !"""
 " " " " " " " " " " 
"r%   r{   r    )basesnsr   r   r:   r;   r<   r=   r>   r   r?   r@   modulerN   c                  ddl m} t        |t              s|&||u st        |t              r||}}n|t        d      ||urt        |t              st        d|d      |dk(  r|}||||||	d}||d	}t        j                  d
k\  r|
|d<   ||d<   ||d<   n-|
durt        d      |durt        d      |durt        d      t        j                  dk\  r||d<   n|durt        d      t        j                  dk\  r"|	 t        j                  d      xs d}||d<   n|t        d      d}t        j                  dk\  r;|t         j"                  t"        fv rt%        j&                  t"        |      }d}||d<   n|t         j"                  urt        d      t!        j(                  | fd |i||}|s4|j+                  dd       |j+                  dd       t#        |fi |d!|i}|S # t        $ rg t        j                  t        t              5  t        j                  d      j                  j                  dd      }ddd       n# 1 sw Y   nxY wY Aw xY w)"a  Make a new dynamically created dataclass with PyTree integration.

    The dataclass name will be ``cls_name``. ``fields`` is an iterable of either (name), (name, type),
    or (name, type, Field) objects. If type is omitted, use the string :data:`typing.Any`. Field
    objects are created by the equivalent of calling :func:`field` (name, type [, Field-info]).

    The ``namespace`` parameter is the PyTree registration namespace which should be a string. The
    ``namespace`` in the original :func:`dataclasses.make_dataclass` function is renamed to ``ns``
    to avoid conflicts.

    The remaining parameters are passed to :func:`dataclasses.make_dataclass`.
    See :func:`dataclasses.make_dataclass` for more information.

    Args:
        cls_name: The name of the dataclass.
        fields (Iterable[str | tuple[str, Any] | tuple[str, Any, Any]]): An iterable of either
            (name), (name, type), or (name, type, Field) objects.
        namespace (str): The registry namespace used for the PyTree registration.
        ns (dict or None, optional): The namespace used in dynamic type creation.
            See :func:`dataclasses.make_dataclass` and the builtin :func:`type` function for more
            information.
        **kwargs (optional): Optional keyword arguments passed to :func:`dataclasses.make_dataclass`.

    Returns:
        type: The dynamically created dataclass with PyTree integration.
    r   rH   Nz?make_dataclass() missing 1 required keyword-only argument: 'ns'rQ   rP   rR   rJ   )r   rB   r*   r>   r   r?   Tz@make_dataclass() got an unexpected keyword argument 'match_args'Fz=make_dataclass() got an unexpected keyword argument 'kw_only'z;make_dataclass() got an unexpected keyword argument 'slots'rK   r@   zBmake_dataclass() got an unexpected keyword argument 'weakref_slot')r+         __main__r7   r   z<make_dataclass() got an unexpected keyword argument 'module'r-   )rB   rN   z?make_dataclass() got an unexpected keyword argument 'decorator'rr   rB   )rk   rI   rp   rc   rq   r6   r2   r3   _getframemodulenameAttributeError
contextlibsuppress
ValueError	_getframe	f_globalsr1   r4   rC   	functoolspartialmake_dataclasspop)cls_namerr   r   r   r   r   r:   r;   r<   r=   r>   r   r?   r@   r   rN   rB   rw   dataclass_kwargsmake_dataclass_kwargsregistered_by_decoratorrE   s                         r"   r   r     s   ` G)T"i&7!!ZC%8%r	BZ]^^((Is1K>ym1MNNB$	 " 
 7")3&&-#$)!	4	Z[[		WXX	e	UVV
7"+7(	U	"\]]
7">T003Az
 +1h'		VWW#
7"..	::!)))yII&*#-6k*	+//	/YZZ,,   	C #Wd+^T2E/E9EJ7 " T((D T ]]1-77;;J
SFT T TTs*   G0 0'I 0I	I I	I I )r!   r   r   r   r   r   r   bool | Noner   r   r   dict[Any, Any] | Noner   #bool | Literal[dataclasses.MISSING]r   
str | Noner   r   rj   r   )r'   zCallable[[], _T]r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   r   )r!   r   r'   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   r   )r   r   r   r   r:   r   r;   r   r<   r   r=   r   r>   r   r   r   r?   r   r@   r   rB   rq   rj   zCallable[[_TypeT], _TypeT])rE   r   r   r   r   r   r:   r   r;   r   r<   r   r=   r   r>   r   r   r   r?   r   r@   r   rB   rq   rj   r   r   )rE   z_TypeT | Noner   r   r   r   r:   r   r;   r   r<   r   r=   r   r>   r   r   r   r?   r   r@   r   rB   rq   rj   z#_TypeT | Callable[[_TypeT], _TypeT])$r   rq   rr   z6Iterable[str | tuple[str, Any] | tuple[str, Any, Any]]r   ztuple[type, ...]r   zdict[str, Any] | Noner   r   r   r   r:   r   r;   r   r<   r   r=   r   r>   r   r   r   r?   r   r@   r   r   r   rN   z_DataclassDecorator[_TypeT]rB   rq   rj   r   )"__doc__
__future__r   r   r4   r   rl   r2   rs   typingr   r   r   r   r	   r
   r   typing_extensionsr   collections.abcr   __all__rn   r   __annotations__r   r   typer   r5   r#   rC   r{   r   r    r%   r"   <module>r      s%  *\ #     
   U U U 1 (
 !K
  (! d ! T]T]		& 
 &*3>3F3F#  	
   $ 1 
   
 
 &*3>3F3F#%  	
   $ 1 
   
 
 &*3>3F3F#


 
 	

 
 $
 1
 

 
 	
 

 &&&..&*3>3F3F#E'E' E' 	E'
 E' E' E' $E' 1E' 
E' E' 	E'P 
 %
% % 		%
 % % % % % % % %  % 
%  

 	 	
  	          
$ uh/w w	w 	w
 w 	w w w w w w w w w )w 0wt"(6* "4 ! $-8-B-B%yy Cy
 y 	y y y 	y y y y y y y  !y" #y$ +%y& 'y( )yr%   