
    $Shx                    "   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return4tuple[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 be 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           _/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/optree/integrations/numpy.pyr   r   *   sX    J $!	  FH '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     (LL$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3D"'$--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5d28D>>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
0b2>
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!DT"(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$bhtnn33H==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3F33333E55f55555FI(//00G

0
0
0
0K
0
0
000 
.!D!DV!D!D!DEE:GVLL
 	
 nQQQQ&QQQRRG/7FK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~~btbbQSQYZ^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 )NrO   rP   rQ   c                >    g | ]\  }}|                     |          S r8   )reshape)r0   chunkr6   s      r#   r=   z0_unravel_leaves_single_dtype.<locals>.<listcomp>   s(    NNN\UEEMM%  NNNr$   )r-   r6   rR   splitr   )rL   rK   r!   chunkss       r#   rG   rG      s     
x~~'"+''+~ + +$+ + +
 
 	

 XdGCRCL))FNNXff5M5M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     
 
 
#ue MM%  ''..
 
 
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cxccU`ccc
 
 	
 XdGCRCL))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$   