
    קg                         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dS )zLAssorted utilities, which do not need anything other then torch and stdlib.
    N   )_dtypes_implc                 x    t          | t                    rdS 	 t          |            n# t          $ r Y dS w xY wdS )NFT)
isinstancestrlen	Exception)seqs    N/var/www/html/ai-engine/env/lib/python3.11/site-packages/torch/_numpy/_util.pyis_sequencer      sR    #s uC   uu4s   ) 
77c                       e Zd ZdS )	AxisErrorN__name__
__module____qualname__     r   r   r              Dr   r   c                       e Zd ZdS )UFuncTypeErrorNr   r   r   r   r   r      r   r   r   c                 J    | | j         |k    r|                     |          } | S N)dtypeto)tensorr   s     r   cast_if_neededr       s*    V\U225!!Mr   c                     t          j        | j                  dk     r+|                     t          j                    j                  } | S )N   )r   	_categoryr   r   default_dtypesfloat_dtype)xs    r   cast_int_to_floatr$   '   s<    ag&&**DD,..:;;Hr   c                 f    | | 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)   /   sY    ER$SSSTSSTTT	Avv
d
Ir   Fc                    t          |           t          t          fvr'	 t          j        |           g} n# t
          $ r Y nw xY wt          fd| D                       } |sdt          t          t          t          |                               t          |           k    r$rt          d d          t          d          | S )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`
    c                 2    g | ]}t          |          S r   )r)   ).0r&   r(   r'   s     r   
<listcomp>z(normalize_axis_tuple.<locals>.<listcomp>\   s&    IIIb&r499IIIr   zrepeated axis in `z
` argumentzrepeated axis)typetuplelistoperatorindex	TypeErrorr   setmapint
ValueError)axisr'   r(   allow_duplicates    `` r   normalize_axis_tupler:   8   s    < Dzz%&&	N4(()DD 	 	 	D	 IIIIIDIIIJJD .s3s3~~#6#6773t99DD 	.E'EEEFFF_---Ks   7 
AAc                 ^    | | S t          |           dk    rt          d          | d         S )Nr   zdoes not handle tuple axisr   )r   NotImplementedErrorr8   s    r   allow_only_single_axisr>   e   s3    |
4yyA~~!">???7Nr   c                     t                    t          t          fvrft                    t          |           z   }t	          |          t          |           fdt          |          D             }|S )Nc                 :    g | ]}|v rd nt                    S r   )next)r,   r&   r8   shape_its     r   r-   z expand_shape.<locals>.<listcomp>t   s+    KKKR"**QQ$x..KKKr   )r.   r0   r/   r   r:   iterrange)	arr_shaper8   out_ndimshaperC   s    `  @r   expand_shaperI   m   sw    Dzz$&&w4yy3y>>)Hh//DIHKKKKK5??KKKELr   c                     |-d|z  }|                      |                                          } n*t          | j        |          }|                     |          } | S )NrA   )expand
contiguousrI   rH   reshape)r   r8   r'   rH   s       r   apply_keepdimsrN   x   sV    |tu%%0022V\400&&Mr   r=   c                 H    | t          d |D                       }|dfS || fS )z#Flatten the arrays if axis is None.Nc              3   >   K   | ]}|                                 V  d S r   )flatten)r,   ars     r   	<genexpr>z$axis_none_flatten.<locals>.<genexpr>   s*      77

777777r   r   r/   )r8   tensorss     r   axis_none_flattenrV      s7    |77w777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   r3   r   )ttarget_dtyperX   can_casts       r   typecast_tensorr^      s    , )H8AG\7;;; 
A17 A AA A6=A A A
 
 	
 !\***r   c                 >    t          fd| D                       S )Nc              3   :   K   | ]}t          |          V  d S r   )r^   )r,   r[   rX   r\   s     r   rS   z#typecast_tensors.<locals>.<genexpr>   s/      LLqL'::LLLLLLr   rT   )rU   r\   rX   s    ``r   typecast_tensorsra      s*    LLLLLGLLLLLLr   c                     	 t          j        |           }n7# t          $ r*}d|  dt          |           d}t	          |          d }~ww xY w|S )Nzfailed to convert z! to ndarray. 
Internal error is: .)torch	as_tensorr	   r   r<   )objr   emesgs       r   _try_convert_to_tensorri      sj    (%% ( ( (TCTT3q66TTT!$'''( Ms    
A%AAc                    t          | t          j                  r| }nt          j                    }t          j        t          j        t          j                             	 t          |           }t          j        |           n# t          j        |           w xY wt          ||          }||j
        z
  }|dk    r |                    d|z  |j        z             }|r|                                }|S )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   rA   )r   rd   Tensorget_default_dtypeset_default_dtyper   get_default_dtype_forfloat32ri   r   r'   viewrH   clone)rf   r   copyndminr   default_dtype
ndim_extras          r   _coerce_to_tensorrv      s    6 #u|$$ 3 /11 B5= Q QRRR	3+C00F#M2222E#M2222 FE**F $JA~~TJ.=>>   Ms   "B Bc                     ddl m} t          |           dk    rt                      S t          |           dk    rp| d         }t	          ||          r|j        S t	          |t                    r:g }|D ]&}t          |          }|                    |           't          |          S |S t	          | t                    sJ t          |           S )zHConvert all ndarrays from `inputs` to tensors. (other things are intact)r   )ndarrayr   )	_ndarrayrx   r   r7   r   r   r/   ndarrays_to_tensorsappend)inputsrx   input_result	sub_input
sub_results         r   rz   rz      s    !!!!!!
6{{a||	V		fg&& 		= && 	F# * *	0;;
j))))== M&%((((("6***r   r   )NF)NFr   )__doc__r1   rd    r   r   r7   
IndexErrorr   r3   RuntimeErrorr   r   r$   r)   r:   r>   rI   rN   rV   r^   ra   ri   rv   rz   r   r   r   <module>r      s             	 	 	 	 	
J 	 	 		 	 	 	 	Y 	 	 	       * * * *Z       &*     + + +@M M M  5 5 5 5p+ + + + +r   