
    `iI                     n   d Z ddlZddlZddlmZ ddlmZmZ ddl	m
Z
 ddlZd Zd Zd Z ej                    d	             Z ej                    d
             Z ej                    d             Zd Zd Zd Zd Zd#dZd#dZd$dZd$dZd%dZd%dZd&dZ ej        dddddd !          Z d" Z!dS )'a  
Signal processing B-Splines

Some of the functions defined here were ported directly from CuSignal under
terms of the MIT license, under the following notice:

Copyright (c) 2019-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
    N)apply_iir_sos)_symiirorder1_nd_symiirorder2_nd)BSplinec                    t          d ||fD                       rt          d          | j        }|j        dk    r)|t          j        k    rt          j        nt          j        }n4|t          j        k    s|j        dk    rt          j        }nt          j	        }| 
                    |d          } |
                    |d          }|
                    |d          }|ddd                                         |ddd                                         ft          j        j        j                            | d	fd
ddd          S )a}  Convolve with a 2-D separable FIR filter.

    Convolve the rank-2 input array with the separable filter defined by the
    rank-1 arrays hrow, and hcol. Mirror symmetric boundary conditions are
    assumed. This function can be used to find an image given its B-spline
    representation.

    The arguments `hrow` and `hcol` must be 1-dimensional and of off length.

    Args:
        input (cupy.ndarray): The input signal
        hrow (cupy.ndarray): Row direction filter
        hcol (cupy.ndarray): Column direction filter

    Returns:
        cupy.ndarray: The filtered signal

    .. seealso:: :func:`scipy.signal.sepfir2d`
    c              3   H   K   | ]}|j         d k    p|j        dz  dk    V  dS )      r   N)ndimsize).0xs     p/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/signal/_bsplines.py	<genexpr>zsepfir2d.<locals>.<genexpr>;   s7      
@
@a16Q;)!&1*/
@
@
@
@
@
@    z2hrow and hcol must be 1 dimensional and odd lengthcr
   F)copyN)r   r	   c                     |          S )N )ifilterss    r   <lambda>zsepfir2d.<locals>.<lambda>I   s     r   reflectr   )any
ValueErrordtypekindcupy	complex64
complex128float32itemsizefloat64astypeconjcupyxscipyndimage_filters_run_1d_correlates)inputhrowhcolr   r   s       @r   sepfir2dr/   '   s;   ( 
@
@D$<
@
@
@@@ OMNNNKEzS"'4>"9"9t	$,		%.A"5"5LLUL++E;;u5;))D;;u5;))DDDbDz  $ttt*//"3"34G;'::v++++T9aA A Ar   c                     t          t          j        | t                              } t	          j        t          j        g d          d          } ||           }d|| dk     | dk    z  <   |S )Nr   )      g      g      ?      ?Fextrapolater   r2   r3   )absr   asarrayfloatr   basis_elementr   bouts      r   
_quadraticr=   L   sw    DL%((())A+++,,%	A 	A 	AA
!A$$C"#CTa#gJr   c                     t          j        | t                    } t          j        t          j        g d          d          } ||           }d|| dk     | dk    z  <   |S )Nr1   )r   r   r	   r
   Fr4   r   r?   r
   )r   r7   r8   r   r9   r:   s      r   _cubicr@   U   sl    Qe$$$A&&&''U	< 	< 	<A
!A$$CCRAEJr   c           
         dd| z  z
  d| z  t          j        dd| z  z             z  z   }t          j        t          j        d| z  dz
            t          j        |                    }d| z  dz
  t          j        |          z
  d| z  z  }|t          j        d| z  d| z  t          j        dd| z  z             z  z   |z            z  }||fS )Nr	   `            0   )r   sqrtarctan2)lamxiomegrhos       r   _coeff_smoothrM   ^   s    	
R#XS49Qs]#;#;;	;B<	#)a-00$)B--@@D8a<$)B--'BH
5C
		cBHtyS3Y777	72=? ? ?C9r   c                     |t          j        |          z  || z  z  t          j        || dz   z            z  t          j        | d          z  S )Nr	   r   )r   singreater)kcsrL   omegas       r   _hcrT   h   sK    % C1H-!a%0I0IILB  !r   c                 n   ||z  d||z  z   z  d||z  z
  z  dd|z  |z  t          j        d|z            z  z
  |dz  z   z  }d||z  z
  d||z  z   z  t          j        |          z  }t          j        |           }|||z  z  t          j        ||z            |t          j        ||z            z  z   z  S )Nr	   r
      )r   costanr6   rO   )rQ   rR   rL   rS   c0gammaaks          r   _hsr\   n   s    
r'Qs]
#q39}
5q3w}txE	2222SAX=?Bs]q39}-?E	!Br	>utx
';';;;= =r   c           	         t          |          \  }}dd|z  t          j        |          z  z
  ||z  z   }t          |           }t          j        |f| j        j                  }t          j        |          }t          d|||          | d         z  t          j	        t          |dz   |||          | z            z   }t          d|||          | d         z  t          d|||          | d         z  z   t          j	        t          |dz   |||          | z            z   }	t          j
        dd||	f         }
t          j        |
          }
t          j
        |dddd|z  t          j        |          z  ||z  f         }t          j        |          }t          | dd          ||
| j                  \  }}t          j
        ||	|f         }t          j	        t          ||||          t          |dz   |||          z   | d d d         z            }t          j	        t          |dz
  |||          t          |dz   |||          z   | d d d         z            }	t          j
        dd||	f         }
t          j        |
          }
t          |dd d         ||
| j                  \  }}t          j
        |d d d         |	|f         }|S )Nr	   r
   r   r?   zir   r   )rM   r   rW   lenzerosr   chararangerT   sumr_
atleast_2dr   r\   )signallambrL   rS   rR   KyprQ   state_0state_1r_   coef_ys                 r   _cubic_smooth_coeffrq   x   s   t$$JC	
QWtx&	&s	2BFA	QD&,+	,	,BAA1b#u%%q	1xAE2sE22V;<<=G1b#u%%q	11b#u%%q	12xAE2sE22V;<<=G 
Aw'	(B			B72q!QS48E?? :C#IEFD?4  D &*drFFFEB	'2%	&B hAr3..AE2sE2236<TTrTlC D DGhAE2sE22AE2sE2236<TTrTlC D DG 
Aw'	(B			BBFFTbEEEDAq$$B$')*AHr   c                    dt          j        d          z   }t          |           }|t          j        |          z  }|dk    rB| d         |t          j        || z            z  z   }||dz
  z  |z  }t          j        |          S t           j        dddt          j        || z            f         }t          j        |          }t           j        dddd| df         }t          j        |          }t          | ||d| j	                  \  }}||dz
  z  ||dz
           z  }	t           j        ddd|	f         }t          j        |          }t           j        | ddd| df         }t          j        |          }t          |dd d         ||| j	                  \  }}t           j        |d d d         |	f         }|d	z  S )
Nr?   rD   r	   r   Fr_   	apply_firr   r   r^         @
r   rG   ra   rd   re   
atleast_1drf   rg   r   r   
rh   r_   rj   powersyplusoutputstatern   ro   out_lasts
             r   _cubic_coeffr~      s   	dill	BFA4;q>>!FAvvq	B&6/!:!:::rAv&v&&&GAq!TXfvo6667EOE""E71aAsA%&D?4  D
 VTeu#)<1 1 1HE1 R!V}uQU|+HGAq!X%&EOE""E7B31a"a'(D?4  D
 bf"ftV\; ; ;IFAWVDDbD\8+,FC<r   c                    ddt          j        d          z  z   }t          |           }|t          j        |          z  }|dk    rB| d         |t          j        || z            z  z   }||dz
  z  |z  }t          j        |          S t           j        dddt          j        || z            f         }t          j        |          }t           j        dddd| df         }t          j        |          }t          | ||d| j	                  \  }}||dz
  z  ||dz
           z  }	t           j        ddd|	f         }t          j        |          }t           j        | ddd| df         }t          j        |          }t          |dd d	         ||| j	        
          \  }}t           j        |d d d	         |	f         }|dz  S )Nr`   r
          @r	   r   Frs   r?   r   r^          @rv   rx   s
             r   _quadratic_coeffr      s   	a$)C.. 	 BFA4;q>>!FAvvq	B&6/!:!:::rAv&v&&&GAq!TXfvo6667EOE""E71aAsA%&D?4  D
 VTeu#)<1 1 1HE1 R!V}uQU|+HGAq!X%&EOE""E7B31a"a'(D?4  D
 bf"ftV\; ; ;IFAWVDDbD\8+,FC<r   c                 P   t          j        dd| z  z             }dd| z  z
  d| z  |z  z   }t          j        t          j        d| z  dz
  |z                      }t          j        |          }d| z  dz
  |z
  d| z  z  t          j        d| z  d| z  |z  z             z  |z  }||fS )NrD   rE   r	   rB   rC         ?rF   )nprG   arctan)ri   tmprJ   rS   tmp2rs         r   compute_root_from_lambdar      s    
'!cDj.
!
!C	
R$YdS	(BIbgsTzC/256677E72;;D
t)a-$
29	-	"T'BIO+	-	-
.04
5Ae8Or           c                 L    |dk    rt          | |          S t          |           S )a  
    Compute cubic spline coefficients for rank-1 array.

    Find the cubic spline coefficients for a 1-D signal assuming
    mirror-symmetric boundary conditions. To obtain the signal back from the
    spline representation mirror-symmetric-convolve these coefficients with a
    length 3 FIR window [1.0, 4.0, 1.0]/ 6.0 .

    Parameters
    ----------
    signal : ndarray
        A rank-1 array representing samples of a signal.
    lamb : float, optional
        Smoothing coefficient, default is 0.0.

    Returns
    -------
    c : ndarray
        Cubic spline coefficients.

    See Also
    --------
    cspline1d_eval : Evaluate a cubic spline at the new set of points.

    r   )rq   r~   rh   ri   s     r   	cspline1dr     s+    4 s{{"64000F###r   c                 J    |dk    rt          d          t          |           S )a  Compute quadratic spline coefficients for rank-1 array.

    Parameters
    ----------
    signal : ndarray
        A rank-1 array representing samples of a signal.
    lamb : float, optional
        Smoothing coefficient (must be zero for now).

    Returns
    -------
    c : ndarray
        Quadratic spline coefficients.

    See Also
    --------
    qspline1d_eval : Evaluate a quadratic spline at the new set of points.

    Notes
    -----
    Find the quadratic spline coefficients for a 1-D signal assuming
    mirror-symmetric boundary conditions. To obtain the signal back from the
    spline representation mirror-symmetric-convolve these coefficients with a
    length 3 FIR window [1.0, 6.0, 1.0]/ 8.0 .

    r   z.Smoothing quadratic splines not supported yet.)r   r   r   s     r   	qspline1dr   $  s*    6 s{{IJJJ'''r   r   c                    t          j        |          |z
  t          |          z  }t          j        || j                  }|j        dk    r|S t          |           }|dk     }||dz
  k    }||z   }t          | ||                    ||<   t          | d|dz
  z  ||         z
            ||<   ||         }|j        dk    r|S t          j        || j                  }	t          j        |dz
            	                    t                    dz   }
t          d          D ]>}|
|z   }|                    d|dz
            }|	| |         t          ||z
            z  z  }	?|	||<   |S )aD  Evaluate a cubic spline at the new set of points.

    `dx` is the old sample-spacing while `x0` was the old origin. In
    other-words the old-sample points (knot-points) for which the `cj`
    represent spline coefficients were at equally-spaced points of:

      oldx = x0 + j*dx  j=0...N-1, with N=len(cj)

    Edges are handled using mirror-symmetric boundary conditions.

    Parameters
    ----------
    cj : ndarray
        cublic spline coefficients
    newx : ndarray
        New set of points.
    dx : float, optional
        Old sample-spacing, the default value is 1.0.
    x0 : int, optional
        Old origin, the default value is 0.

    Returns
    -------
    res : ndarray
        Evaluated a cubic spline points.

    See Also
    --------
    cspline1d : Compute cubic spline coefficients for rank-1 array.

    r1   r   r	   r
   rV   )r   r7   r8   
zeros_liker   r   ra   cspline1d_evalfloorr%   intrangeclipr@   cjnewxdxx0resNcond1cond2cond3resultjlowerr   thisjindjs                 r   r   r   E  sm   @ L#uRyy0D
/$bh
/
/
/C
x1}}
BA1HEAENEemET%[L11CJAQK$u+$=>>CJ;DyA~~
_T222FZq!!((--1F1XX 2 2
zz!QU##"T(VD5L1111CJJr   c                    t          j        |          |z
  |z  }t          j        |          }|j        dk    r|S t	          |           }|dk     }||dz
  k    }||z   }t          | ||                    ||<   t          | d|dz
  z  ||         z
            ||<   ||         }|j        dk    r|S t          j        |          }	t          j        |dz
                                t                    dz   }
t          d          D ]>}|
|z   }|
                    d|dz
            }|	| |         t          ||z
            z  z  }	?|	||<   |S )ah  Evaluate a quadratic spline at the new set of points.

    Parameters
    ----------
    cj : ndarray
        Quadratic spline coefficients
    newx : ndarray
        New set of points.
    dx : float, optional
        Old sample-spacing, the default value is 1.0.
    x0 : int, optional
        Old origin, the default value is 0.

    Returns
    -------
    res : ndarray
        Evaluated a quadratic spline points.

    See Also
    --------
    qspline1d : Compute quadratic spline coefficients for rank-1 array.

    Notes
    -----
    `dx` is the old sample-spacing while `x0` was the old origin. In
    other-words the old-sample points (knot-points) for which the `cj`
    represent spline coefficients were at equally-spaced points of::

      oldx = x0 + j*dx  j=0...N-1, with N=len(cj)

    Edges are handled using mirror-symmetric boundary conditions.

    r   r	   r
   r3   rD   )r   r7   r   r   ra   qspline1d_evalr   r%   r   r   r   r=   r   s                 r   r   r   }  sY   D L#r)D
/$

C
x1}}
BA1HEAENEemET%[L11CJAQK$u+$=>>CJ;DyA~~
_T""FZs
##**3//!3F1XX 6 6
zz!QU##"T(Zu5555CJJr         c                    |dk    rIdt          j        d          z   }t          | | dz  ||d          }t          || dz  ||d          }|S t          |          \  }}t	          | |||d          }t	          ||||d          }|S )a8  
    Coefficients for 2-D cubic (3rd order) B-spline.

    Return the third-order B-spline coefficients over a regularly spaced
    input grid for the two-dimensional input image.

    Parameters
    ----------
    input : ndarray
        The input signal.
    lamb : float
        Specifies the amount of smoothing in the transfer function.
    precision : float
        Specifies the precision for computing the infinite sum needed to apply
        mirror-symmetric boundary conditions.

    Returns
    -------
    output : ndarray
        The filtered signal.
    gqq|?r?   g      @ru   r   	precisionaxisr   )r   rG   r   r   r   )rh   ri   r   r   r<   rS   s         r   	cspline2dr     s    , yvrCxi$&( ( (sQBHa9$%' ' '
'--HAu
61eyr
J
J
JC
35IA
F
F
FCJr   c                     |dk    rt          d          ddt          j        d          z  z   }t          | | dz  ||d          }t          || dz  ||d          }|S )	a=  
    Coefficients for 2-D quadratic (2nd order) B-spline.

    Return the second-order B-spline coefficients over a regularly spaced
    input grid for the two-dimensional input image.

    Parameters
    ----------
    input : ndarray
        The input signal.
    lamb : float
        Specifies the amount of smoothing in the transfer function.
    precision : float
        Specifies the precision for computing the infinite sum needed to apply
        mirror-symmetric boundary conditions.

    Returns
    -------
    output : ndarray
        The filtered signal.
    r   zlambda must be negative or zeror`   r
   r   r   r   r   )r   r   rG   r   )rh   ri   r   r   r<   s        r   	qspline2dr     sv    . axx:;;; 	QA
6A28Q)"
M
M
MC
3S!yq
I
I
ICJr         @c                    | j         j        }t          j        g dd          dz  }|dv r}|                     d          } t          | j        |          }t          | j        |          }t          |||          }t          |||          }|d|z  z                       |          }nJ|dv r7t          | |          }t          |||          }|                    |          }nt          d          |S )	a  Smoothing spline (cubic) filtering of a rank-2 array.

    Filter an input data set, `Iin`, using a (cubic) smoothing spline of
    fall-off `lmbda`.

    Parameters
    ----------
    Iin : array_like
        input data set
    lmbda : float, optional
        spline smooghing fall-off value, default is `5.0`.

    Returns
    -------
    res : ndarray
        filtered input data

    )r   g      @r   fru   )FDr   y              ?)r   dzInvalid data type for Iin)
r   rc   r   r7   r%   r   realimagr/   	TypeError)	Iinlmbdaintyper.   ckrckioutroutir<   s	            r   spline_filterr     s    & Y^F<--3Djjoo%((%((T4((T4((b4i''//	:		U##sD$''jj  3444Jr   zT x, int32 nzT outputzR
    output = 1 / sqrt( 2.0 * M_PI * signsq ) * exp( -( x * x ) * r_signsq );
    _gauss_spline_kernel)z
-std=c++11z`const double signsq { ( n + 1 ) / 12.0 };                const double r_signsq { 0.5 / signsq };)options	loop_prepc                 J    t          j        |           } t          | |          S )ax  Gaussian approximation to B-spline basis function of order n.

    Parameters
    ----------
    x : array_like
        a knot vector
    n : int
        The order of the spline. Must be nonnegative, i.e. n >= 0

    Returns
    -------
    res : ndarray
        B-spline basis function values approximated by a zero-mean Gaussian
        function.

    Notes
    -----
    The B-spline basis function can be approximated well by a zero-mean
    Gaussian function with standard-deviation equal to :math:`\sigma=(n+1)/12`
    for large `n` :

    .. math::  \frac{1}{\sqrt {2\pi\sigma^2}}exp(-\frac{x^2}{2\sigma})

    See [1]_, [2]_ for more information.

    References
    ----------
    .. [1] Bouma H., Vilanova A., Bescos J.O., ter Haar Romeny B.M., Gerritsen
       F.A. (2007) Fast and Accurate Gaussian Derivatives Based on B-Splines.
       In: Sgallari F., Murli A., Paragios N. (eds) Scale Space and Variational
       Methods in Computer Vision. SSVM 2007. Lecture Notes in Computer
       Science, vol 4485. Springer, Berlin, Heidelberg
    .. [2] http://folk.uio.no/inf3330/scripting/doc/python/SciPy/tutorial/old/node24.html
    )r   r7   r   )r   ns     r   gauss_spliner   0  s"    F 	QA1%%%r   )r   )r   r   )r   r   )r   )"__doc__r   cupyx.scipy.ndimager'   cupyx.scipy.signal._iir_utilsr   cupyx.scipy.signal._splinesr   r    cupyx.scipy.interpolate._bspliner   numpyr   r/   r=   r@   fuserM   rT   r\   rq   r~   r   r   r   r   r   r   r   r   r   ElementwiseKernelr   r   r   r   r   <module>r      s'   6      7 7 7 7 7 7 J J J J J J J J 4 4 4 4 4 4    "A "A "AJ        ! ! !
 = = =5 5 5p" " "J" " "J  $ $ $ $@( ( ( (B5 5 5 5p7 7 7 7t" " " "J   D" " " "J .t- 8
 
 
 $& $& $& $& $&r   