
    sg                         d Z ddlZddlZddlmZ d Z G d dee      Z G d d	e	e
      Zd
 Zd ZddZddZd Zd Zd ZdddZd Zd Zd ZddZd Zy)zLAssorted utilities, which do not need anything other then torch and stdlib.
    N   )_dtypes_implc                 \    t        | t              ry	 t        |        y# t        $ r Y yw xY w)NFT)
isinstancestrlen	Exception)seqs    E/var/www/html/venv/lib/python3.12/site-packages/torch/_numpy/_util.pyis_sequencer      s4    #sC   s    	++c                       e Zd Zy)	AxisErrorN__name__
__module____qualname__     r   r   r          r   r   c                       e Zd Zy)UFuncTypeErrorNr   r   r   r   r   r      r   r   r   c                 J    | | j                   |k7  r| j                  |      } | S N)dtypeto)tensorr   s     r   cast_if_neededr       s&    V\\U25!Mr   c                     t        j                  | j                        dk  r-| j                  t        j                         j
                        } | S )N   )r   	_categoryr   r   default_dtypesfloat_dtype)xs    r   cast_int_to_floatr$   '   s;    agg&*DD,,.::;Hr   c                 X    | | cxk  r|k  sn t        d|  d|       | dk  r| |z  } | S )Nzaxis z) is out of bounds for array of dimension r   )r   )axndimargnames      r   normalize_axis_indexr)   /   s?    ER$%t#LTFSTT	Av
d
Ir   c           
      j   t        |       t        t        fvr	 t        j                  |       g} t        | D cg c]  }t        |||       c}      } |sJt        t        t        t        |                   t        |       k7  r|rt        d| d      t        d      | S # t
        $ r Y }w xY wc c}w )a  
    Normalizes an axis argument into a tuple of non-negative integer axes.

    This handles shorthands such as ``1`` and converts them to ``(1,)``,
    as well as performing the handling of negative indices covered by
    `normalize_axis_index`.

    By default, this forbids axes from being specified multiple times.
    Used internally by multi-axis-checking logic.

    Parameters
    ----------
    axis : int, iterable of int
        The un-normalized index or indices of the axis.
    ndim : int
        The number of dimensions of the array that `axis` should be normalized
        against.
    argname : str, optional
        A prefix to put before the error message, typically the name of the
        argument.
    allow_duplicate : bool, optional
        If False, the default, disallow an axis from being specified twice.

    Returns
    -------
    normalized_axes : tuple of int
        The normalized axis index, such that `0 <= normalized_axis < ndim`
    zrepeated axis in `z
` argumentzrepeated axis)typetuplelistoperatorindex	TypeErrorr)   r   setmapint
ValueError)axisr'   r(   allow_duplicater&   s        r   normalize_axis_tupler7   8   s    < Dz%&	NN4()D DIb&r49IJDs3s3~#673t9D1'*EFF_--K  		 Js   B! B0!	B-,B-c                 F    | | S t        |       dk7  rt        d      | d   S )Nr   zdoes not handle tuple axisr   )r   NotImplementedErrorr5   s    r   allow_only_single_axisr;   e   s,    |
4yA~!">??7Nr   c                     t        |      t        t        fvr|f}t        |      t        |       z   }t	        ||      }t        |       }t        |      D cg c]  }||v rdn
t        |       }}|S c c}w )Nr   )r+   r-   r,   r   r7   iterrangenext)	arr_shaper5   out_ndimshape_itr&   shapes         r   expand_shaperD   m   sq    Dz$&w4y3y>)Hh/DIH;@?KR"*Q$x.0KEKL Ls   A2c                     |&d|z  }| j                  |      j                         } | S t        | j                  |      }| j	                  |      } | S )Nr   )expand
contiguousrD   rC   reshape)r   r5   r'   rC   s       r   apply_keepdimsrJ   x   sS    |tu%002 M V\\40&Mr   r:   c                 :    | t        d |D              }|dfS || fS )z#Flatten the arrays if axis is None.c              3   <   K   | ]  }|j                           y wr   )flatten).0ars     r   	<genexpr>z$axis_none_flatten.<locals>.<genexpr>   s     7

7s   r   r,   )r5   tensorss     r   axis_none_flattenrS      s+    |7w77z}r   c           	          t         j                  } || j                  ||      st        d| j                   d| d| d      t	        | |      S )a  Dtype-cast tensor to target_dtype.

    Parameters
    ----------
    t : torch.Tensor
        The tensor to cast
    target_dtype : torch dtype object
        The array dtype to cast all tensors to
    casting : str
        The casting mode, see `np.can_cast`

     Returns
     -------
    `torch.Tensor` of the `target_dtype` dtype

     Raises
     ------
     ValueError
        if the argument cannot be cast according to the `casting` rule

    )castingzCannot cast array data from z to z according to the rule '')r   can_cast_implr   r0   r   )ttarget_dtyperU   can_casts       r   typecast_tensorr[      s_    , ))HAGG\7;*177) 4~5gYaA
 	
 !\**r   c                 0    t        fd| D              S )Nc              3   8   K   | ]  }t        |        y wr   )r[   )rN   rX   rU   rY   s     r   rP   z#typecast_tensors.<locals>.<genexpr>   s     LqL':Ls   rQ   )rR   rY   rU   s    ``r   typecast_tensorsr^      s    LGLLLr   c                     	 t        j                  |       }|S # t        $ r"}d|  dt        |       d}t	        |      d }~ww xY w)Nzfailed to convert z! to ndarray. 
Internal error is: .)torch	as_tensorr	   r   r9   )objr   emesgs       r   _try_convert_to_tensorrf      sS    (% M  (#C5(J3q6(RST!$''(s    	A?Ac                    t        | t        j                        r| }nkt        j                         }t        j                  t        j                  t        j                               	 t        |       }t        j                  |       t        ||      }||j                  z
  }|dkD  r!|j                  d|z  |j                  z         }|r|j                         }|S # t        j                  |       w xY w)a  The core logic of the array(...) function.

    Parameters
    ----------
    obj : tensor_like
        The thing to coerce
    dtype : torch.dtype object or None
        Coerce to this torch dtype
    copy : bool
        Copy or not
    ndmin : int
        The results as least this many dimensions
    is_weak : bool
        Whether obj is a weakly typed python scalar.

    Returns
    -------
    tensor : torch.Tensor
        a tensor object with requested dtype, ndim and copy semantics.

    Notes
    -----
    This is almost a "tensor_like" coersion function. Does not handle wrapper
    ndarrays (those should be handled in the ndarray-aware layer prior to
    invoking this function).
    r   rF   )r   ra   Tensorget_default_dtypeset_default_dtyper   get_default_dtype_forfloat32rf   r   r'   viewrC   clone)rc   r   copyndminr   default_dtype
ndim_extras          r   _coerce_to_tensorrs      s    6 #u||$ //1 B B5== QR	3+C0F##M2 FE*F $JA~TJ.=> M ##M2s   )C C5c                  R   ddl m} t        |       dk(  r
t               S t        |       dk(  r_| d   }t	        ||      r|j
                  S t	        |t              r0g }|D ]  }t        |      }|j                  |         t        |      S |S t	        | t              sJ t        |       S )zHConvert all ndarrays from `inputs` to tensors. (other things are intact)r   )ndarrayr   )	_ndarrayru   r   r4   r   r   r,   ndarrays_to_tensorsappend)inputsru   input_result	sub_input
sub_results         r   rw   rw      s    !
6{a|	V	fg&== &F# *	0;
j)* = M&%((("6**r   r   )NF)NFr   )__doc__r.   ra    r   r   r4   
IndexErrorr   r0   RuntimeErrorr   r   r$   r)   r7   r;   rD   rJ   rS   r[   r^   rf   rs   rw   r   r   r   <module>r      s      	
J 		Y 	*Z &* +@M5p+r   