o
    X۷i0                     @  s   d dl mZ d dlZd dlZd dlZd dlZd dlmZ dd Zdd Z	edd	 Z
ed
d Zedd Zdd Zdd Zdd ZdddZdd Zdd ZdS )    )annotationsN)RankWarningc                   s"   dd   fdd}t |S )Nc                 S  sZ   t | tjr	| jS t| rt| S t | tjr)t| } | jdkr%| S tdt	d)N   z)Multidimensional inputs are not supportedzUnsupported type)

isinstancecupypoly1d_coeffsisscalar
atleast_1dndarrayndim
ValueError	TypeErrorx r   M/home/ubuntu/vllm_env/lib/python3.10/site-packages/cupy/lib/_routines_poly.py_get_coeffs   s   



z'_wraps_polyroutine.<locals>._get_coeffsc                    sf    fdd| D }| }t dd | D r|S t|tjr#t|S t|tr1tdd |D S J )Nc                   s   g | ]} |qS r   r   .0r   )r   r   r   
<listcomp>   s    z7_wraps_polyroutine.<locals>.wrapper.<locals>.<listcomp>c                 s  s    | ]
}t |tj V  qd S )N)r   r   r   r   r   r   r   	<genexpr>   s    z6_wraps_polyroutine.<locals>.wrapper.<locals>.<genexpr>c                 S  s   g | ]}t |qS r   )r   r   r   r   r   r   r   "   s    )allr   r   r   r   tuple)argscoeffsoutr   funcr   r   wrapper   s   

z#_wraps_polyroutine.<locals>.wrapper)	functoolsupdate_wrapper)r   r   r   r   r   _wraps_polyroutine   s   r"   c                 C  s8  | }|j dkr,|jd |jd kr,|jd dkr,t|| jr(tj|}ntd|j dkr>|j	t
|jjdd}ntd|jdkrIdS d|jd   }t|df|j}|d	d	df d tj||d	|jdf d
 |dkr|d }tjj|d	| ||d	 d}|dksx|dd	|jd f S )a  Computes the coefficients of a polynomial with the given roots sequence.

    Args:
        seq_of_zeros (cupy.ndarray): a sequence of polynomial roots.

    Returns:
        cupy.ndarray: polynomial coefficients from highest to lowest degree.

    .. warning::

        This function doesn't support general 2d square arrays currently.
        Only complex Hermitian and real symmetric 2d arrays are allowed.

    .. seealso:: :func:`numpy.poly`

       r   r   KOnly complex Hermitian and real symmetric 2d arrays are supported currentlyFcopyz.Input must be 1d or non-empty square 2d array.g      ?N)r   full)r   shaper   array_equalconjTlinalgeigvalshNotImplementedErrorastypemintypecodedtypecharr   size
bit_lengthzerosfillnegative_mathmisc_fft_convolve)seq_of_zerosr   r3   ar   r   r   poly(   s&   ,

"r=   c                 C  sP   | j |j k r|| } }t|| j |j  df}|jt| |dd}|| 7 }|S )a<  Computes the sum of two polynomials.

    Args:
        a1 (scalar, cupy.ndarray or cupy.poly1d): first input polynomial.
        a2 (scalar, cupy.ndarray or cupy.poly1d): second input polynomial.

    Returns:
        cupy.ndarray or cupy.poly1d: The sum of the inputs.

    .. seealso:: :func:`numpy.polyadd`

    r   Fr%   )r3   r   padr/   result_typea1a2r   r   r   r   polyaddS   s   
rC   c                 C  s   | j d |j d kr+t| |j d | j d  df}|jt| |dd}||8 }|S t|| j d |j d  df}|jt| |dd}|d| |  8 }|S )aJ  Computes the difference of two polynomials.

    Args:
        a1 (scalar, cupy.ndarray or cupy.poly1d): first input polynomial.
        a2 (scalar, cupy.ndarray or cupy.poly1d): second input polynomial.

    Returns:
        cupy.ndarray or cupy.poly1d: The difference of the inputs.

    .. seealso:: :func:`numpy.polysub`

    r   Fr%   r#   )r(   r   r>   r/   r?   r@   r   r   r   polysubi   s     rD   c                 C  s\   t j| dd} t j|dd}| jdkrt dg| j} |jdkr(t dg|j}t | |S )aD  Computes the product of two polynomials.

    Args:
        a1 (scalar, cupy.ndarray or cupy.poly1d): first input polynomial.
        a2 (scalar, cupy.ndarray or cupy.poly1d): second input polynomial.

    Returns:
        cupy.ndarray or cupy.poly1d: The product of the inputs.

    .. seealso:: :func:`numpy.polymul`

    f)trimr   g        )r   
trim_zerosr3   arrayr1   convolve)rA   rB   r   r   r   polymul   s   

rJ   c                 C  s\   |dkrdS |dkr| S |d dkrt t| | |d S t| t t| | |d d S )Nr   r   r#   )_polypowr   rI   )r   nr   r   r   _polypow_direct   s   "rM   c                 C  s   |dkrdS |dkr| S t jj| | d}|dkrt| |S |dkrf| jjdkr2t jjt jj}}n	t jj	t jj
}}| jd | d }dd l}|jj|}|| |}t |||}	||	|}
|
d | S J )Nr   r   r'   directfftc)r   r8   r9   _choose_conv_methodrM   r1   kindrO   ifftrfftirfftr3   cupyx.scipy.fftscipynext_fast_lenpower)r   rL   methodrO   rS   out_sizecupyxr3   fxfyyr   r   r   rK      s&   


rK   c                 C  s,   | j jdkr| jtjddS | jtjddS )NrP   Fr%   )r1   rR   r/   numpy
complex128float64r   r   r   r   _polyfit_typecast   s   rc   Fc                 C  s  | j jdkr|j jdkrtd|j tjkrtdt| } t|}t|}|dk r.t	d| j
dkr7td| jdkr@td	|j
dk sJ|j
d
krNtd| j|jd krZtdtjj| |dddddf }|}|durt|}|j
dkr~td|j| jkrtd||dddf 9 }|j
d
kr|dddf }||9 }|du r| jt| j j }tt|jdd}	||	 }tj|||\}
}}}|j
dkr|	dd}	|
|	 }
|d }||kr|sd}tj|tdd |r|j jdkrt|}|
||||fS |rEtjt|j|}|t|	|	 }|dkr#d}n| j|kr1|| j|  }nt	d|j
dkr?|d }|
|| fS |
S )a  Returns the least squares fit of polynomial of degree deg
    to the data y sampled at x.

    Args:
        x (cupy.ndarray): x-coordinates of the sample points of shape (M,).
        y (cupy.ndarray): y-coordinates of the sample points of shape
            (M,) or (M, K).
        deg (int): degree of the fitting polynomial.
        rcond (float, optional): relative condition number of the fit.
            The default value is ``len(x) * eps``.
        full (bool, optional): indicator of the return value nature.
            When False (default), only the coefficients are returned.
            When True, diagnostic information is also returned.
        w (cupy.ndarray, optional): weights applied to the y-coordinates
            of the sample points of shape (M,).
        cov (bool or str, optional): if given, returns the coefficients
            along with the covariance matrix.

    Returns:
        cupy.ndarray or tuple:
        p (cupy.ndarray of shape (deg + 1,) or (deg + 1, K)):
            Polynomial coefficients from highest to lowest degree
        residuals, rank, singular_values, rcond         (cupy.ndarray, int, cupy.ndarray, float):
            Present only if ``full=True``.
            Sum of squared residuals of the least-squares fit,
            rank of the scaled Vandermonde coefficient matrix,
            its singular values, and the specified value of ``rcond``.
        V (cupy.ndarray of shape (M, M) or (M, M, K)):
            Present only if ``full=False`` and ``cov=True``.
            The covariance matrix of the polynomial coefficient estimates.

    .. warning::

        cupy.exceptions.RankWarning: The rank of the coefficient matrix in the
        least-squares fit is deficient. It is raised if ``full=False``.

    .. seealso:: :func:`numpy.polyfit`

    ebz0float16 x and bool y are not currently supportedzfloat16 y are not supportedr   zexpected deg >= 0r   zexpected 1D vector for xzexpected non-empty vector for xr#   zexpected 1D or 2D array for yz$expected x and y to have same lengthNz expected a 1-d array for weightsz(expected w and y to have the same length)axisz!Polyfit may be poorly conditioned   )
stacklevelrP   unscaledzJthe number of data points must exceed order to scale the covariance matrix.N) r1   r2   rR   r.   r`   float16r   rc   intr   r   r3   r(   r   
polynomial
polyvanderfinfoepssqrtsquaresumr,   lstsqreshapewarningswarnr   absoluteinvdotr+   outer)r   r_   degrcondr'   wcovlhsrhsscalerP   residsranksordermsgbasefactorr   r   r   polyfit   sr   )

"




r   c                 C  sn  t | tjr	| j} t | tjr| jdkrtd| jdkr!tdt |tjrZt	|jd}ttj
dg|d}ttj
dg|d}| ddd D ]}|||  }|| }qK|S t |tjset|}t	| jd|}| j|dd	} | jdkrt|j|S |tjkr|  | | d  S t|stj||dd
 }|tj| j|d }| ddd | jd|dS )a  Evaluates a polynomial at specific values.

    Args:
        p (cupy.ndarray or cupy.poly1d): input polynomial.
        x (scalar, cupy.ndarray): values at which the polynomial
        is evaluated.

    Returns:
        cupy.ndarray or cupy.poly1d: polynomial evaluated at x.

    .. warning::

        This function doesn't currently support poly1d values to evaluate.

    .. seealso:: :func:`numpy.polyval`

    r   z%p must be 1d ndarray or poly1d objectr   zp must be 1d array)r1   Nrf   Fr%   rk   )rg   r1   )r   r   r   r   r   r   r   r   r`   r?   rH   asarrayr1   typer/   r3   r5   r(   bool_anyr	   arangert   )pr   r1   resprodrP   r   r   r   polyval6  s4   





r   c                 C  s   t | tjr	| j} | jjdkrtd| jdkrtd| j	dk r&t
g S tjj| ddd g\} | j	dk r>t
g S | j	dkr]| d  | d  d }| d dkr[|jtj}|S tjj| }t|| jrttj|}ntd	|| jS )
a!  Computes the roots of a polynomial with given coefficients.

    Args:
        p (cupy.ndarray or cupy.poly1d): polynomial coefficients.

    Returns:
        cupy.ndarray: polynomial roots.

    .. warning::

        This function doesn't support currently polynomial coefficients
        whose companion matrices are general 2d square arrays. Only those
        with complex Hermitian or real symmetric 2d arrays are allowed.

        The current `cupy.roots` doesn't guarantee the order of results.

    .. seealso:: :func:`numpy.roots`

    re   z boolean inputs are not supportedr   z"0-dimensional input is not allowedr#   Nrf   r   r$   )r   r   r   r   r1   rR   r.   r   r   r3   rH   rn   	polyutils	as_seriesrealr/   r`   rb   polycompanionr)   r*   r+   r,   r-   )r   r   cmatrixr   r   r   rootse  s*   





r   )NFNF)
__future__r   r    rw   r`   r   cupy.exceptionsr   r"   r=   rC   rD   rJ   rM   rK   rc   r   r   r   r   r   r   r   <module>   s(    +




s/