
    VpfI                       d dl mZ d dlmZmZ d dlmZ d dlZd dlZd dl	m
Z
mZmZ d dlZd dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZmZ d dlmZmZmZmZmZmZ d dlZ ee!cZ!Z"ee#cZ#Z$ ed          Z% ej&        d          Z' ej&        dej(                  Z) ej&        dej(                  Z* ej&        dej(                  Z+ ej&        d          Z, G d de          Z-dVdZ.dWdZ/dXdZ0	 	 	 	 	 	 dYdZd-Z1 eej2        d.          Z3d[d3Z4d\d6Z5d]d7Z6d]d8Z7d]d9Z8d]d:Z9d^d>Z:d_d@Z;dAdBdCd`dEZ<d`dFZ=d`dGZ>e>Z?d`dHZ@d[dIZAd[dJZBd[dKZC eejD        dL          d]dM            ZEdadRZFejD        dbdU            ZGdS )c    )annotations)CallableSequence)partialN)Any
NamedTupleTypeVar)api)config)core)dtypes)lax)safe_zipsafe_map)Array	ArrayLikeDimSizeDType	DTypeLikeShape_Tz
(?=[A-Za-z_])z\n(?=[^\n]{3,15}\n-{3,15})z$^([\w., ]+=)?\s*[\w\.]+\([\w\W]*?\)$z^\s+\.\.\s+versionadded::z:doc:`(.*?)\s*<.*?>`c                  V    e Zd ZU dZded<   dZded<   dZded<   dZded<   i Zd	ed
<   dS )	ParsedDocz
  docstr: full docstring
  signature: signature from docstring.
  summary: summary from docstring.
  front_matter: front matter before sections.
  sections: dictionary of section titles to section content.
  
str | Nonedocstr str	signaturesummaryfront_matterdict[str, str]sectionsN)	__name__
__module____qualname____doc____annotations__r   r   r    r"        S/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/_src/numpy/util.pyr   r   -   sn           )',(r)   r   r   r   returnc                   | |                                  st          |           S t                              d |           } d| }}t                              |          }|r0|                                }| |                                d         }|                    d          \  }}}t          j
        |                    d                    }t                              |          }|r0|                                }||                                d         }|}|sS|                    d                              d          \  }}}t          j
        |                    d                    }d}d|z   }t                              |          }t                              |d                   s|^}}d |D             }	t          | ||||	          S )zParse a standard numpy-style docstring.

  Args:
    docstr: the raw docstring from a function
  Returns:
    ParsedDoc: parsed version of the docstring
  Nc                8    |                                  d          S )Nr   )groups)matchs    r*   <lambda>z!_parse_numpydoc.<locals>.<lambda>I   s    U\\^^A&( r)   r   
r   c                H    i | ]}|                     d d          d         | S )r1      r   )split).0sections     r*   
<dictcomp>z#_parse_numpydoc.<locals>.<dictcomp>c   s-    MMMWgmmD!$$Q'MMMr)   )r   r   r   r    r"   )stripr   _docreferencesub_numpy_signature_rer/   groupend	partitiontextwrapdedentlstrip_section_breakr4   )
r   r   bodyr/   	firstline_r   r    section_listr"   s
             r*   _parse_numpydocrG   <   s    ^6<<>>^V ((&2 2& T)

#
#D
)
)%
  I%))++,,D~~d++)Q	T**	+	+$

#
#D
)
)%
 I		D'	 .{{4((22488GQ?4;;t,,--D,	$%%d++,			l1o	.	. /".L<MMMMM(	&Iw ,x
A 
A 
A Ar)   rC   r   r!   c                    |                      dd          \  }}}|dk    sJ |r|                    d          rJ t                               |          }d |D             S )z,Parse the Parameters section of a docstring.r1      
Parameters-c                x    i | ]7}|                     d           d                              d          d         |8S z : r   , r>   r5   ps     r*   r7   z%_parse_parameters.<locals>.<dictcomp>o   >    	J	J	J!!++e

Q

)
)$
/
/
2A	J	J	Jr)   )r4   r8   _parameter_break)rC   title	underlinecontent
parameterss        r*   _parse_parametersrX   i   sq    "jjq11%G	,					/9??3/////%%g..*	J	Jz	J	J	JJr)   extra_paramsc                t    t                               |                     d                    }d |D             S )z1Parse the extra parameters passed to implements()r1   c                x    i | ]7}|                     d           d                              d          d         |8S rM   rO   rP   s     r*   r7   z'_parse_extra_params.<locals>.<dictcomp>u   rR   r)   )rS   r4   r8   )rY   rW   s     r*   _parse_extra_paramsr\   r   s7    %%l&8&8&>&>??*	J	Jz	J	J	JJr)   Tr   rJ   Returns
Referencesr(   original_funCallable[..., Any] | None
update_docboollax_descriptionr"   Sequence[str]skip_paramsmoduleCallable[[_T], _T]c                *      fd}|S )a  Decorator for JAX functions which implement a specified NumPy function.

  This mainly contains logic to copy and modify the docstring of the original
  function. In particular, if `update_doc` is True, parameters listed in the
  original function that are not supported by the decorated function will
  be removed from the docstring. For this reason, it is important that parameter
  names match those in the original numpy function.

  Args:
    original_fun: The original function being implemented
    update_doc: whether to transform the numpy docstring to remove references of
      parameters that are supported by the numpy version but not the JAX version.
      If False, include the numpy docstring verbatim.
    lax_description: a string description that will be added to the beginning of
      the docstring.
    sections: a list of sections to include in the docstring. The default is
      ["Parameters", "Returns", "References"]
    skip_params: a list of strings containing names of parameters accepted by the
      function that should be skipped in the parameter list.
    extra_params: an optional string containing additional parameter descriptions.
      When ``update_doc=True``, these will be added to the list of parameter
      descriptions in the updated doc.
    module: an optional string specifying the module from which the original function
      is imported. This is useful for objects such as ufuncs, where the module cannot
      be determined from the original function itself.
  c                @  	 | _         r| _        | S t          dd           }t          dt          | dt          |                               }	 pj        }| d| }n4# t
          $ r' t          j        j        rt          d d          Y nw xY w|r	 t          |          }rd|j        v rt          t          | d|           dd           	t          |j        d                   }
r"|                    t          
                     	fd	|                                D             }|r=d
d                    d |                                D                       z   |j        d<   n|j        d= |j        r|j                                        dz   nd}|d| dz  }r|d                                z   dz   z  }|dz  }|j        r"|d|j                                        z   dz   z  }fd|j                                        D             }|r|dd                    |          z   dz   z  }n #  t          j        j        r j        }Y nxY w|| _        dD ]4}	 t          |          }t)          | ||           %# t
          $ r Y 1w xY w| S )Nr&   r#   .z	function z< defines no __module__; pass module keyword to implements().rJ   __wrapped____code__c                :    i | ]\  }}	|j         v r|v||S N)co_varnames)r5   rQ   desccoderf   s      r*   r7   z1implements.<locals>.decorator.<locals>.<dictcomp>   sE     2 2 2GAt LA1A,A,A[00 4000r)   zParameters
----------
r1   c              3     K   | ]9\  }}t                               |          d                                          V  :dS r   N)_versionaddedr4   rstrip)r5   rQ   rq   s      r*   	<genexpr>z0implements.<locals>.decorator.<locals>.<genexpr>   sY       ; ;#At &++D11!4;;== ; ; ; ; ; ;r)   r   z&
LAX-backend implementation of :func:`z`.
z
*Original docstring below.*
c              3  N   K   | ]\  }}|v 	|                                 V   d S ro   )r8   )r5   r6   rV   r"   s      r*   rw   z0implements.<locals>.decorator.<locals>.<genexpr>   sF       1 1-=Wg#x// !////1 1r)   z

)r#   r%   )__np_wrapped__r&   getattrr   r$   AttributeErrorr   enable_checksvalue
ValueErrorrG   r"   rX   updater\   itemsjoinr   r8   r    setattr)wrapped_funr   namemodparsedrW   kept_sectionsattrr}   rr   rY   rd   rg   r`   r"   rf   rb   s            @r*   	decoratorzimplements.<locals>.decorator   s   !-K	 .-\9d33F<W[*cR]N^N^-_-_``D-l-c
 __d__dd	  q q q			# qo\ooopppq qq
  +&*& (( 	.,&/99m[II:W[\\$()FGG* A1,??@@@2 2 2 2 2z/?/?/A/A 2 2 2*  .ii ; ;'1'7'7'9'9; ; ; ; ;; OL)) -28.H%%''$..bFDFFFF 	:
D?00222T9
9&33  	>
D6.44666=
=&1 1 1 1AVAVAXAX 1 1 1 	=
D6;;}555<
<&&% 	
% K, * **d++ 	T5))))     s1   	A' '.BBF I   I,J
JJr(   )r`   rb   rd   r"   rf   rY   rg   r   s   ``````` r*   
implementsr   x   sU    FE E E E E E E E E E EL 
r)   )canonicalizefun_nameargsr   list[Array]c                $   t          |          dk     rd |D             S d |D             t          j        j        r*t	          j         fdt          |          D             S t          fddd         D                       rd |D             S d	 D             }t          |          dk     rd
 |D             S t          j        j        dk    rt          |            t          t	          j                   fd|D             S )zHApply NumPy-style broadcasting, making args shape-compatible for lax.py.rI   c                6    g | ]}t          j        |          S r(   r   asarrayr5   args     r*   
<listcomp>z"promote_shapes.<locals>.<listcomp>   "    ---CK---r)   c                6    g | ]}t          j        |          S r(   npshaper   s     r*   r   z"promote_shapes.<locals>.<listcomp>   s     ,,,bhsmm,,,r)   c                6    g | ]\  }}t          |          S r(   _broadcast_to)r5   r   shp	res_shapes      r*   r   z"promote_shapes.<locals>.<listcomp>   s'    NNNSmC++NNNr)   c              3  d   K   | ]*}t          d                    t          |          k    V  +dS rt   lenr5   sshapess     r*   rw   z!promote_shapes.<locals>.<genexpr>   s8      ::!S^^s1vv%::::::r)   r3   Nc                6    g | ]}t          j        |          S r(   r   r   s     r*   r   z"promote_shapes.<locals>.<listcomp>   "    111SC  111r)   c                0    h | ]}|t          |          S r(   r   )r5   r   s     r*   	<setcomp>z!promote_shapes.<locals>.<setcomp>   s#    ;;;cs;S;;;r)   c                6    g | ]}t          j        |          S r(   r   r   s     r*   r   z"promote_shapes.<locals>.<listcomp>   r   r)   allowc                :    g | ]}t          j        |          S r(   )r   broadcast_to_rank)r5   r   result_ranks     r*   r   z"promote_shapes.<locals>.<listcomp>   s&    HHHC%c;77HHHr)   )
r   r   dynamic_shapesr}   r   broadcast_shapeszipallnumpy_rank_promotion _rank_promotion_warning_or_error)r   r   nonscalar_ranksr   r   r   s      @@@r*   promote_shapesr      sH   YY]]------,,t,,,F" I &/iNNNNCf<M<MNNNN	::::vabbz:::	:	: 211D1111;;V;;;o	_			!	!11D1111&,77
*8V
<
<
<#.788HHHH4HHHHr)   r   Sequence[Shape]c                   t           j        j        dk    rRd}t          j        |                    | d                    t          t          |                                         d S t           j        j        dk    rKd}t          |                    | d                    t          t          |                                        d S )NwarnzFollowing NumPy automatic rank promotion for {} on shapes {}. Set the jax_numpy_rank_promotion config option to 'allow' to disable this warning; for more information, see https://jax.readthedocs.io/en/latest/rank_promotion_warning.html. raisezOperands could not be broadcast together for {} on shapes {} and with the config option jax_numpy_rank_promotion='raise'. For more information, see https://jax.readthedocs.io/en/latest/rank_promotion_warning.html.)
r   r   r}   warningsr   formatr   mapr   r~   )r   r   msgs      r*   r   r      s     &&00OC M#**XsxxC0@0@'A'ABBCCCCC"(G33OC SZZ#((3sF3C3C*D*DEE
F
FF 43r)   c                     t          |           dk     rd | D             S t          j        |  \  t          j        d          fd| D             S )z=Convenience function to apply Numpy argument dtype promotion.rI   c                6    g | ]}t          j        |          S r(   r   r   s     r*   r   z"promote_dtypes.<locals>.<listcomp>  r   r)   Tallow_extended_dtypec                <    g | ]}t          j        |          S r(   r   _convert_element_type)r5   xto_dtype	weak_types     r*   r   z"promote_dtypes.<locals>.<listcomp>  s(    LLL!C%a9==LLLr)   )r   r   _lattice_result_typecanonicalize_dtype)r   r   r   s    @@r*   promote_dtypesr     sm     	YY]]------ 5t<Hi(MMMHLLLLLtLLLLr)   c                     t          j        |  \  }t          j        |d          }t          j        |          fd| D             S )zgConvenience function to apply Numpy argument dtype promotion.

  Promotes arguments to an inexact type.Tr   c                <    g | ]}t          j        |          S r(   r   )r5   r   to_dtype_inexactr   s     r*   r   z*promote_dtypes_inexact.<locals>.<listcomp>  9     
 
 
 
#A'7
C
C 
 
 
r)   )r   r   r   to_inexact_dtype)r   r   r   r   s     @@r*   promote_dtypes_inexactr     sn     3T:(I&xdKKK(,X66
 
 
 
 

 
 
 r)   c                     t          j        |  \  }t          j        |          }t          j        |          fd| D             S )zqConvenience function to apply Numpy argument dtype promotion.

  Promotes arguments to a numeric (non-bool) type.c                <    g | ]}t          j        |          S r(   r   )r5   r   to_dtype_numericr   s     r*   r   z*promote_dtypes_numeric.<locals>.<listcomp>*  r   r)   )r   r   r   to_numeric_dtype)r   r   r   r   s     @@r*   promote_dtypes_numericr   #  i     3T:(I&x00(,X66
 
 
 
 

 
 
 r)   c                     t          j        |  \  }t          j        |          }t          j        |          fd| D             S )zfConvenience function to apply Numpy argument dtype promotion.

  Promotes arguments to a complex type.c                <    g | ]}t          j        |          S r(   r   )r5   r   to_dtype_complexr   s     r*   r   z*promote_dtypes_complex.<locals>.<listcomp>5  r   r)   )r   r   r   to_complex_dtype)r   r   r   r   s     @@r*   promote_dtypes_complexr   .  r   r)   dtyper   r   c                Z    t          j        t          j        d|                     j        S )zFReturns the float type of the real/imaginary parts of a complex dtype.r(   )r   abszerosr   )r   s    r*   _complex_elem_typer   9  s!    	U##	$	$	**r)   r   c                    t          | t          j                  p8t          | t                    p#t	          | d          pt          j        |           S )N__jax_array__)
isinstancer   ndarrayr   hasattrisscalar)r   s    r*   
_arrayliker   >  sI    
Q

#
# 8z!U';'; 8
!_
%
%8)+Q9r)   F   )emit_warning
stacklevelr   c                  t          | t                    sJ d|              t          d |D                       rt          d t	          |          D                       \  }}|  dt          |           d| d}|r!t          j        |dz   t          |           d	S t          |
                    | t          |          |                    d	S )
z4Check if all args fit JAX's definition of arraylike.fun_name must be a string. Got c              3  6   K   | ]}t          |           V  d S ro   r   r   s     r*   rw   z"check_arraylike.<locals>.<genexpr>F  s+      --Z__	------r)   c              3  B   K   | ]\  }}t          |          ||fV  d S ro   r   r5   ir   s      r*   rw   z"check_arraylike.<locals>.<genexpr>G  sH       , ,C%c??,QH , , , , , ,r)   z+ requires ndarray or scalar arguments, got z at position rk   z/ In a future JAX release this will be an error.)categoryr   N)r   r   anynext	enumeratetyper   r   DeprecationWarning	TypeErrorr   )r   r   r   r   posr   r   s          r*   check_arrayliker   C  s   	Hc	"	"PP$Ph$P$PPPP------- < , ,9T?? , , , , ,HC
`
`$s))
`
`Z]
`
`
`C <mCKK/JH H H H H H cjj499c::;;;< <r)   c                4   t          | t                    sJ d|              t          d |D                       r\t          d t	          |          D                       \  }}d}t          |                    | t          |          |                    d S )Nr   c              3  >   K   | ]}t          |          p|d u  V  d S ro   r   r   s     r*   rw   z*check_arraylike_or_none.<locals>.<genexpr>S  s4      >>#joo,	->>>>>>r)   c              3  F   K   | ]\  }}t          |          s|||fV  d S ro   r   r   s      r*   rw   z*check_arraylike_or_none.<locals>.<genexpr>T  sE       = =C&sOO=/2{ H/:{{{= =r)   zF{} requires ndarray, scalar, or None arguments, got {} at position {}.)r   r   r   r   r   r   r   r   )r   r   r   r   r   s        r*   check_arraylike_or_noner   Q  s    	Hc	"	"PP$Ph$P$PPPP>>>>>>> : = =9T?? = = = = =HC
RC
CJJxcC88
9
99	: :r)   c                ^    t          d |D                       rt          d|  d          dS )z,Check if none of the args have dtype float0.c              3  Z   K   | ]&}t          j        |          t           j        k    V  'd S ro   )r   r   float0r   s     r*   rw   z#check_no_float0s.<locals>.<genexpr>\  s3      <<c		fm	+<<<<<<r)   zCalled a   with a float0 array. float0s do not support any operations by design because they are not compatible with non-trivial vector spaces. No implicit dtype conversion is done. You can use np.zeros_like(arr, dtype=np.float) to cast a float0 array to a regular zeros array. 
If you didn't expect to get a float0 you might have accidentally taken a gradient with respect to an integer argument.N)r   r   r   r   s     r*   check_no_float0sr  Z  s]    <<t<<<<< A
	@( 	@ 	@ 	@A A AA Ar)   c           
        d |D             }t          t          |                    dk     rdS t          d |D                       rvt          |          dk    r(t          |  dt	          |d                    d          t          |  d	d
                    t          t          |                     d          dS )zDCheck if args don't match and none of the args have typed prng dtypec                6    g | ]}t          j        |          S r(   )r   r   r   s     r*   r   z&check_for_prngkeys.<locals>.<listcomp>j  s"    222cS!!222r)   rI   Nc              3  T   K   | ]#}t          j        |t           j                  V  $d S ro   )r   
issubdtypeprng_key)r5   dts     r*   rw   z%check_for_prngkeys.<locals>.<genexpr>m  s1      EEB	2v	/	/EEEEEEr)   r3   z does not accept dtype r   rk   z does not accept dtypes rN   )r   setr   r   r   r   r   )r   r   
arg_dtypess      r*   check_for_prngkeysr  h  s    22T222*ZA
FEE*EEEEE 
:!AAC
1,>,>AAAC C C OOTYYs3
7K7K-L-LOOO   r)   c                x    t          | g|R   t          | g|R   t          | g|R   t          | gt	          | R  S )zGConvenience function to apply Numpy argument shape and dtype promotion.)r   _check_no_float0sr  r   r   r  s     r*   promote_argsr  w  s_    ("T""""H$t$$$$X%%%%%		9>4#8	9	9	99r)   c                x    t          | g|R   t          | g|R   t          | g|R   t          | gt	          | R  S ro   )r   r  r  r   r   r  s     r*   promote_args_numericr    s`    ("T""""H$t$$$$X%%%%%		A#94#@	A	A	AAr)   c                x    t          | g|R   t          | g|R   t          | g|R   t          | gt	          | R  S )zyConvenience function to apply Numpy argument shape and dtype promotion.

  Promotes non-inexact types to an inexact type.)r   r  r  r   r   r  s     r*   promote_args_inexactr    sb     ("T""""H$t$$$$X%%%%%		A#94#@	A	A	AAr)   )inlinec                     d | D             rt          fdD                       rd | D             S t          j         fd| D             S )z7Like Numpy's broadcast_arrays but doesn't return views.c                6    g | ]}t          j        |          S r(   r   r   s     r*   r   z%_broadcast_arrays.<locals>.<listcomp>  s     ***cBHSMM***r)   c              3  N   K   | ]}t          j        d          |          V   dS rt   )r   definitely_equal_shaper   s     r*   rw   z$_broadcast_arrays.<locals>.<genexpr>  s4      QQQt26!9a@@QQQQQQr)   c                6    g | ]}t          j        |          S r(   r   r   s     r*   r   z%_broadcast_arrays.<locals>.<listcomp>  r   r)   c                0    g | ]}t          |          S r(   r   )r5   r   result_shapes     r*   r   z%_broadcast_arrays.<locals>.<listcomp>  s#    	;	;	;s-\
*
*	;	;	;r)   )r   r   r   )r   r  r   s    @@r*   _broadcast_arraysr    s     +*T***&	 .3QQQQ&QQQQQ .------%v.,	;	;	;	;d	;	;	;;r)   arrr   DimSize | Shaper   c                6   t          d|            t          | t                    r| nt          j        |           } t          |t
                    st          j        |          dk    r|f}t          j	        |          }t          j
        |           }t          j        ||          r| S t          |          t          |          k     rt          d|d|          t          |          t          |          z
  }||d          }t          d t          ||          D                       }|dk     s|s%d}t          |                    ||                    t          j        | |t          t%          |t          |                                        S )Nbroadcast_tor   z;Cannot broadcast to shape with fewer dimensions: arr_shape=z shape=c              3  J   K   | ]\  }}t          j        |d |g          V  dS )r3   N)r   definitely_equal_one_of_dim)r5   arr_dshape_ds      r*   rw   z _broadcast_to.<locals>.<genexpr>  sS       L L' 5ea\JJ L L L L L Lr)   z?Incompatible shapes for broadcasting: {} and requested shape {})r   r   r   r   r   tupler   ndimr   canonicalize_shaper   r  r   r~   r   r   r   broadcast_in_dimrange)r  r   	arr_shapenlead
shape_tail
compatibler   s          r*   r   r     s   .#&&&#u%%;3;s+;+;#	E5	!	! bgenn&9&9HE

!%
(
(%hsmm)	 E22 MJ
5zzC	NN""
^^^V[^^
_
__JJY'EuvvJ L L+3Iz+J+JL L L L LJqyy
yMcszz)U33444UE%s5zz2J2J,K,KLLLr)   	conditionyc                   ||#t          d                    ||                    t          j        t	          |           t          j                  s't          j        | t          j        |                     } t          ||          \  }}t          j
        |           dk    rt          ||          \  }}nt          | ||          \  } }}	 t          j        |j                  }n	#  d}Y nxY w|st          j        | ||          n|S )NzeEither both or neither of the x and y arguments should be provided to jax.numpy.where, got {} and {}.r   F)r~   r   r   r	  _dtypebool_r   ne_zeror   r(  r  r   is_empty_shaper   select)r0  r   r1  x_arry_arris_always_emptys         r*   _wherer<    s	   Y!)
 FfQll$ $ $ 
vi(("(	3	3 8y#)I"6"677I	1		$!QWY1$Q**LE55/	1a@@Iue)%+66OOOOO4C	NIue	,	,	,Ns   C* *C0)r   r   r+   r   )rC   r   r+   r!   )rY   r   r+   r!   )Tr   r]   r(   NN)r`   ra   rb   rc   rd   r   r"   re   rf   re   rY   r   rg   r   r+   rh   )r   r   r   r   r+   r   )r   r   r   r   )r   r   r+   r   )r   r   r+   r   )r   r   r+   rc   )r   r   r   r   )r  r   r   r   r+   r   )r0  r   r   r   r1  r   r+   r   )H
__future__r   collections.abcr   r   	functoolsr   rer?   typingr   r   r	   r   jax._srcr
   r   r   r   jax._src.laxr   jax._src.utilr   r   jax._src.typingr   r   r   r   r   r   numpyr   r   
unsafe_zipr   
unsafe_mapr   compilerS   	MULTILINErB   r;   ru   r9   r   rG   rX   r\   r   r   r3  r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  jitr  r   r<  r(   r)   r*   <module>rL     sM   # " " " " " . . . . . . . .       				  + + + + + + + + + +                                , , , , , , , , N N N N N N N N N N N N N N N N    CZCZWT]]2:/00 92<HH bj!H",WW 
7FF
233         
      *A *A *A *AZK K K KK K K K E!##i i i i iV 
D	1	1	1I I I I2G G G GM M M M         + + + +
9 9 9 9
 =Ba < < < < < <: : : :
A 
A 
A 
A %    : : : :B B B BB B B B 	< < < <M M M M4 O O O 	O O Or)   