§
    5P„jœ  ã                  ó"  — U d Z ddlmZ ddlZddlZddlZddlmZmZ ddl	m
Z
 ddlZddlmZ ddlmZmZ ddlmZmZ dd	lmZ g d
¢Z ede¦  «        Zded<    edej        ¦  «        Zded<   	 d1dddœd2d„ZeZd3d!„Zd4d%„Zd5d&„Z d6d+„Z!d7d0„Z"dS )8zIntegration with NumPy.é    )ÚannotationsN)ÚAnyÚCallable)Ú	TypeAlias)Ú	ArrayLike)Útree_flattenÚtree_unflatten)Ú
PyTreeSpecÚPyTreeTypeVar)Úsafe_zip)ÚArrayLikeTreeÚ	ArrayTreeÚ
tree_ravelr   r   r   FÚ )Únone_is_leafÚ	namespaceÚis_leafúCallable[[Any], bool] | NoneÚtreer   Úboolr   ÚstrÚreturnú4tuple[np.ndarray, Callable[[np.ndarray], ArrayTree]]c              óŒ   — t          | |||¬¦  «        \  }}t          |¦  «        \  }}|t          j        t          ||¦  «        fS )a$  Ravel (flatten) a pytree of arrays down to a 1D array.

    >>> tree = {
    ...     'layer1': {
    ...         'weight': np.arange(0, 6, dtype=np.float32).reshape((2, 3)),
    ...         'bias': np.arange(6, 8, dtype=np.float32).reshape((2,)),
    ...     },
    ...     'layer2': {
    ...         'weight': np.arange(8, 10, dtype=np.float32).reshape((1, 2)),
    ...         'bias': np.arange(10, 11, dtype=np.float32).reshape((1,)),
    ...     },
    ... }
    >>> tree  # doctest: +IGNORE_WHITESPACE
    {
        'layer1': {
            'weight': array([[0., 1., 2.],
                             [3., 4., 5.]], dtype=float32),
            'bias': array([6., 7.], dtype=float32)
        },
        'layer2': {
            'weight': array([[8., 9.]], dtype=float32),
            'bias': array([10.], dtype=float32)
        }
    }
    >>> flat, unravel_func = tree_ravel(tree)
    >>> flat
    array([ 6.,  7.,  0.,  1.,  2.,  3.,  4.,  5., 10.,  8.,  9.], dtype=float32)
    >>> unravel_func(flat)  # doctest: +IGNORE_WHITESPACE
    {
        'layer1': {
            'weight': array([[0., 1., 2.],
                             [3., 4., 5.]], dtype=float32),
            'bias': array([6., 7.], dtype=float32)
        },
        'layer2': {
            'weight': array([[8., 9.]], dtype=float32),
            'bias': array([10.], dtype=float32)
        }
    }

    Args:
        tree (pytree): a pytree of arrays and scalars to ravel.
        is_leaf (callable, optional): An optionally specified function that will be called at each
            flattening step. It should return a boolean, with :data:`True` stopping the traversal
            and the whole subtree being treated as a leaf, and :data:`False` indicating the
            flattening should traverse the current object.
        none_is_leaf (bool, optional): Whether to treat :data:`None` as a leaf. If :data:`False`,
            :data:`None` is a non-leaf node with arity 0. Thus :data:`None` is contained in the
            treespec rather than in the leaves list and :data:`None` will remain in the result
            pytree. (default: :data:`False`)
        namespace (str, optional): The registry namespace used for custom pytree node types.
            (default: :const:`''`, i.e., the global namespace)

    Returns:
        A pair ``(array, unravel_func)`` where the first element is a 1D array representing the
        flattened and concatenated leaf values, with ``dtype`` determined by promoting the
        ``dtype``\s of leaf values, and the second element is a callable for unflattening a 1D array
        of the same length back to a pytree of the same structure as the input ``tree``. If the
        input pytree is empty (i.e. has no leaves) then as a convention a 1D empty array of the
        default dtype is returned in the first component of the output.
    )r   r   r   )r   Ú_ravel_leavesÚ	functoolsÚpartialÚ_tree_unravel)r   r   r   r   ÚleavesÚtreespecÚflatÚunravel_flats           ú^/root/disk_3tb/conda_envs/Huy-visual/lib/python3.11/site-packages/optree/integrations/numpy.pyr   r   -   sX   € õJ $ØØØ!Øð	ñ ô Ñ€FˆHõ ' vÑ.Ô.Ñ€Dˆ,Ø•Ô"¥=°(¸LÑIÔIÐIÐIó    r    r
   r"   ú(Callable[[np.ndarray], list[np.ndarray]]r!   ú
np.ndarrayc               ó4   — t          |  ||¦  «        ¦  «        S ©N)r	   )r    r"   r!   s      r#   r   r      s   € õ ˜( L L°Ñ$6Ô$6Ñ7Ô7Ð7r$   r   úlist[np.ndarray]ú;tuple[np.ndarray, Callable[[np.ndarray], list[np.ndarray]]]c               ó\  ‡— | st          j        d¦  «        t          fS t          d„ | D ¦   «         ¦  «        }t          j        | Ž Št          d„ | D ¦   «         ¦  «        }t          d„ | D ¦   «         ¦  «        }t          t          j        |¦  «        ¦  «        }t          ˆfd„|D ¦   «         ¦  «        r;t          j        d„ | D ¦   «         ¦  «        }|t          j
        t          ||¦  «        fS t          j        ˆfd„| D ¦   «         ¦  «        }|t          j
        t          |||‰¦  «        fS )Nr   c              3  ó>   K  — | ]}t          j        |¦  «        V — Œd S r(   )ÚnpÚresult_type©Ú.0Úleafs     r#   ú	<genexpr>z _ravel_leaves.<locals>.<genexpr>’   s,   è è € Ð@Ð@°�œ tÑ,Ô,Ð@Ð@Ð@Ð@Ð@Ð@r$   c              3  ó>   K  — | ]}t          j        |¦  «        V — Œd S r(   )r-   Úsizer/   s     r#   r2   z _ravel_leaves.<locals>.<genexpr>”   s*   è è € Ð3Ð3 D•"”'˜$‘-”-Ð3Ð3Ð3Ð3Ð3Ð3r$   c              3  ó>   K  — | ]}t          j        |¦  «        V — Œd S r(   )r-   Úshaper/   s     r#   r2   z _ravel_leaves.<locals>.<genexpr>•   s*   è è € Ð5Ð5 d•2”8˜D‘>”>Ð5Ð5Ð5Ð5Ð5Ð5r$   c              3  ó$   •K  — | ]
}|‰k    V — Œd S r(   © )r0   ÚdtÚto_dtypes     €r#   r2   z _ravel_leaves.<locals>.<genexpr>˜   s'   øè è € Ð
0Ð
0˜bˆ2�Š>Ð
0Ð
0Ð
0Ð
0Ð
0Ð
0r$   c                ó6   — g | ]}t          j        |¦  «        ‘ŒS r8   )r-   Úravelr/   s     r#   ú
<listcomp>z!_ravel_leaves.<locals>.<listcomp>š   s    € Ð!DÐ!DÐ!D°T¥"¤(¨4¡.¤.Ð!DÐ!DÐ!Dr$   c                ó^   •— g | ])}t          j        |¦  «                             ‰¦  «        ‘Œ*S r8   )r-   r<   Úastype)r0   r1   r:   s     €r#   r=   z!_ravel_leaves.<locals>.<listcomp>¢   s/   ø€ ÐQÐQÐQÀ$�bœh t™nœn×3Ò3°HÑ=Ô=ÐQÐQÐQr$   )r-   ÚzerosÚ_unravel_emptyÚtupler.   Ú	itertoolsÚ
accumulateÚallÚconcatenater   r   Ú_unravel_leaves_single_dtypeÚ_unravel_leaves)r   Úfrom_dtypesÚsizesÚshapesÚindicesÚraveledr:   s         @r#   r   r   ˆ   sD  ø€ ð ð -Ý”˜‘”�^Ð,Ð,åÐ@Ð@¸Ð@Ñ@Ô@Ñ@Ô@€KÝŒ~˜vÐ&€HÝÐ3Ð3¨FÐ3Ñ3Ô3Ñ3Ô3€EÝÐ5Ð5¨fÐ5Ñ5Ô5Ñ5Ô5€FÝ•IÔ(¨Ñ/Ô/Ñ0Ô0€Gå
Ð
0Ð
0Ð
0Ð
0 KÐ
0Ñ
0Ô
0Ñ0Ô0ð 
å”.Ð!DÐ!D¸VÐ!DÑ!DÔ!DÑEÔEˆàÝÔÕ:¸GÀVÑLÔLð
ð 	
õ ŒnÐQÐQÐQÐQÈ&ÐQÑQÔQÑRÔR€GàÝÔ�/¨7°F¸KÈÑRÔRðð r$   c               ó†   — t          j        | ¦  «        dk    r(t          dd› dt          j        | ¦  «        › d�¦  «        ‚g S )N)r   ú0The unravel function expected an array of shape ú, got shape ú.)r-   r6   Ú
ValueError)r!   s    r#   rA   rA   ©   sQ   € Ý	„x��~„~˜ÒÐÝØb¸tÐbÐbÕQSÔQYÐZ^ÑQ_ÔQ_ÐbÐbÐbñ
ô 
ð 	
ð €Ir$   rL   útuple[int, ...]rK   útuple[tuple[int, ...], ...]c               ó  — t          j        |¦  «        | d         fk    r/t          d| d         f› dt          j        |¦  «        › d�¦  «        ‚t          j        || d d…         ¦  «        }d„ t	          ||¦  «        D ¦   «         S )NéÿÿÿÿrO   rP   rQ   c                ó>   — g | ]\  }}|                      |¦  «        ‘ŒS r8   )Úreshape)r0   Úchunkr6   s      r#   r=   z0_unravel_leaves_single_dtype.<locals>.<listcomp>¾   s(   € ÐNÐNÐN¡\ U¨EˆE�MŠM˜%Ñ Ô ÐNÐNÐNr$   )r-   r6   rR   Úsplitr   )rL   rK   r!   Úchunkss       r#   rG   rG   ±   s™   € õ 
„x��~„~˜' "œ+˜Ò'Ð'Ýð+ÀÈÄ¸~ð +ð +Ýœ $™œð+ð +ð +ñ
ô 
ð 	
õ
 ŒX�d˜G C R CœLÑ)Ô)€FØNÐNµX¸fÀfÑ5MÔ5MÐNÑNÔNÐNr$   rI   útuple[np.dtype, ...]r:   únp.dtypec               óð  — t          j        |¦  «        | d         fk    r/t          d| d         f› dt          j        |¦  «        › d�¦  «        ‚t          j        |¦  «        }||k    rt          d|› d|› d�¦  «        ‚t          j        || d d…         ¦  «        }t          j        ¦   «         5  t          j        d¦  «         d„ t          |||¦  «        D ¦   «         cd d d ¦  «         S # 1 swxY w Y   d S )	NrV   rO   rP   rQ   z0The unravel function expected an array of dtype z, got dtype Úignorec                óf   — g | ].\  }}}|                      |¦  «                             |¦  «        ‘Œ/S r8   )rX   r?   )r0   rY   r6   Údtypes       r#   r=   z#_unravel_leaves.<locals>.<listcomp>×   sH   € ð 
ð 
ð 
á#��u˜eð �MŠM˜%Ñ Ô ×'Ò'¨Ñ.Ô.ð
ð 
ð 
r$   )	r-   r6   rR   r.   rZ   ÚwarningsÚcatch_warningsÚsimplefilterr   )rL   rK   rI   r:   r!   Úarray_dtyper[   s          r#   rH   rH   Á   sl  € õ 
„x��~„~˜' "œ+˜Ò'Ð'Ýð+ÀÈÄ¸~ð +ð +Ýœ $™œð+ð +ð +ñ
ô 
ð 	
õ ”. Ñ&Ô&€KØ�hÒÐÝØc¸xÐcÐcÐU`ÐcÐcÐcñ
ô 
ð 	
õ ŒX�d˜G C R CœLÑ)Ô)€FÝ	Ô	 Ñ	"Ô	"ð 
ð 
ÝÔ˜hÑ'Ô'Ð'ð
ð 
å'/°¸ÀÑ'LÔ'Lð
ñ 
ô 
ð
ð 
ð 
ð 
ñ 
ô 
ð 
ð 
ð 
ð 
ð 
ð 
øøøð 
ð 
ð 
ð 
ð 
ð 
s   Â//C+Ã+C/Ã2C/r(   )
r   r   r   r   r   r   r   r   r   r   )r    r
   r"   r%   r!   r&   r   r   )r   r)   r   r*   )r!   r&   r   r)   )rL   rS   rK   rT   r!   r&   r   r)   )rL   rS   rK   rT   rI   r\   r:   r]   r!   r&   r   r)   )#Ú__doc__Ú
__future__r   r   rC   rb   Útypingr   r   Útyping_extensionsr   Únumpyr-   Únumpy.typingr   Ú
optree.opsr   r	   Úoptree.typingr
   r   Úoptree.utilsr   Ú__all__r   Ú__annotations__Úndarrayr   r   Úravel_pytreer   r   rA   rG   rH   r8   r$   r#   ú<module>rs      sÓ  ðð Ð Ð ð
 #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ø Ð Ð Ð Ø €€€Ø  Ð  Ð  Ð  Ð  Ð  Ð  Ð  Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'à Ð Ð Ð Ø "Ð "Ð "Ð "Ð "Ð "à 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ø 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ø !Ð !Ð !Ð !Ð !Ð !ð 7Ð
6Ð
6€ð )˜=¨¸)ÑDÔD€Ð DÐ DÐ DÑ Dà$�} [°"´*Ñ=Ô=€	Ð =Ð =Ð =Ñ =ð -1ðLJð
 ØðLJð LJð LJð LJð LJð LJð^ €ð8ð 8ð 8ð 8ðð ð ð ðBð ð ð ðOð Oð Oð Oð 
ð 
ð 
ð 
ð 
ð 
r$   