U
    -e6                     @   s   d dl Zd dlmZ d dlmZ d dlmZ ddddd	d
dgZdd Z	dd Z
dddZdddZdd	 Zddd
ZdddZdS )    N)eigcomb)convolvedaubqmfcascademorletrickermorlet2cwtc              	      s  t j} dk rtd dkr8d|d }t ||gS  dkrz|dd }|d}|t d| d| d| d| g S  dkrNd|d }d|d	| d
  d|d	||d	   d
  }t |}|dd }t d| d|  }t || }dt | }	|| t |d| |	 d| d|	  d |d|	  d d|	 dg S  dk rv dk r fddt D ddd }
t |
}n. fddt D ddd }
t |
d }t ddg  }t dg}t d D ]Z}|| }d|||d   }dd|  }|| }t	|dk r0|| }|d| g }q|t | }|t 
| |d }|jddd S tddS )aT  
    The coefficients for the FIR low-pass filter producing Daubechies wavelets.

    p>=1 gives the order of the zero at f=1/2.
    There are 2p filter coefficients.

    Parameters
    ----------
    p : int
        Order of the zero at f=1/2, can have values from 1 to 34.

    Returns
    -------
    daub : ndarray
        Return

       zp must be at least 1.            
   g      ?                    ?#   c                    s"   g | ]}t  d  | |d dqS )r   exactr   .0kp W/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/scipy/signal/_wavelets.py
<listcomp>2   s     zdaub.<locals>.<listcomp>Nc                    s*   g | ]"}t  d  | |d dd|  qS )r   r   g      @r   r   r   r   r   r    5   s      z<Polynomial factorization does not work well for p too large.)npsqrt
ValueErrorarrayconjrealrangerootsZpoly1dabssumc)r   r$   r-   ftmpZz1Zz1cZd0Za0Za1PZyjqr   Zyvalpartconstr   r   r   r   	   s^    &
0
(  

 
c                 C   s:   t | d }dd t|d D }| ddd t| S )z
    Return high-pass qmf filter from low-pass

    Parameters
    ----------
    hk : array_like
        Coefficients of high-pass filter.

    Returns
    -------
    array_like
        High-pass filter coefficients.

    r   c                 S   s   g | ]}d dd|d  qS )r   r!   r   r   r   r   r   r   r   r   r    ^   s     zqmf.<locals>.<listcomp>Nr!   )lenr)   r#   r&   )hkNZasgnr   r   r   r   N   s       c                    s:  t | d }|dt|d  kr*td|dk r:tdtjd|d|f \}}td}tj| df }t| }tj|df }td| | d|d }	td| | d d|d }
t	dd||fd	}t
||	d|d
< t
||
d|d< t
||	d|d< t
||
d|d< ||9 }tjd|d|>  tdd|>  }d| }d| }t|d
 \}}tt|d }t|dd|f }t|}|dk r| }| }d|| i}t|d |d |d< d|> }|d |dd|< |d |d|d > d|< t|d |d |dd|< t|d |d |d|d > d|< dg td|d D ]} fdddD }d|| > }|D ]}d}t|D ](}|| dkr|d|d | > 7 }q||dd  }t|d }t|d|f |}|||< |||| d|< t|d|f |||| d|< q~| qX|||fS )a  
    Return (x, phi, psi) at dyadic points ``K/2**J`` from filter coefficients.

    Parameters
    ----------
    hk : array_like
        Coefficients of low-pass filter.
    J : int, optional
        Values will be computed at grid points ``K/2**J``. Default is 7.

    Returns
    -------
    x : ndarray
        The dyadic points ``K/2**J`` for ``K=0...N * (2**J)-1`` where
        ``len(hk) = len(gk) = N+1``.
    phi : ndarray
        The scaling function ``phi(x)`` at `x`:
        ``phi(x) = sum(hk * phi(2x-k))``, where k is from 0 to N.
    psi : ndarray, optional
        The wavelet function ``psi(x)`` at `x`:
        ``phi(x) = sum(gk * phi(2x-k))``, where k is from 0 to N.
        `psi` is only returned if `gk` is not None.

    Notes
    -----
    The algorithm uses the vector cascade algorithm described by Strang and
    Nguyen in "Wavelets and Filter Banks".  It builds a dictionary of values
    and slices for quick reuse.  Then inserts vectors into final vector at the
    end.

    r      zToo many levels.zToo few levels.Nr   r   r!   d)r   r   r4   )r   r   )r   r   dtype01c                    s"   g | ]} D ]}d ||f qqS )z%d%sr   )r   ZxxyyZprevkeysr   r   r       s       zcascade.<locals>.<listcomp>)r5   r#   log2r%   Zogridr$   Zr_r   ZclipemptyZtakearangefloatr   Zargminabsoluter(   r,   dotr)   int)r6   Jr7   nnkks2ZthkZgkZtgkZindx1Zindx2mxphipsiZlamvindsmZbitdicsteplevelZnewkeysZfackeynumposZpastphiiitempr   r@   r   r   b   sh     
 

&&      @      ?Tc                 C   st   t | d t j |d t j | }t d| | }|rP|t d|d  8 }|t d|d  t jd  9 }|S )a)  
    Complex Morlet wavelet.

    Parameters
    ----------
    M : int
        Length of the wavelet.
    w : float, optional
        Omega0. Default is 5
    s : float, optional
        Scaling factor, windowed from ``-s*2*pi`` to ``+s*2*pi``. Default is 1.
    complete : bool, optional
        Whether to use the complete or the standard version.

    Returns
    -------
    morlet : (M,) ndarray

    See Also
    --------
    morlet2 : Implementation of Morlet wavelet, compatible with `cwt`.
    scipy.signal.gausspulse

    Notes
    -----
    The standard version::

        pi**-0.25 * exp(1j*w*x) * exp(-0.5*(x**2))

    This commonly used wavelet is often referred to simply as the
    Morlet wavelet.  Note that this simplified version can cause
    admissibility problems at low values of `w`.

    The complete version::

        pi**-0.25 * (exp(1j*w*x) - exp(-0.5*(w**2))) * exp(-0.5*(x**2))

    This version has a correction
    term to improve admissibility. For `w` greater than 5, the
    correction term is negligible.

    Note that the energy of the return wavelet is not normalised
    according to `s`.

    The fundamental frequency of this wavelet in Hz is given
    by ``f = 2*s*w*r / M`` where `r` is the sampling rate.

    Note: This function was created before `cwt` and is not compatible
    with it.

    Examples
    --------
    >>> from scipy import signal
    >>> import matplotlib.pyplot as plt

    >>> M = 100
    >>> s = 4.0
    >>> w = 2.0
    >>> wavelet = signal.morlet(M, s, w)
    >>> plt.plot(wavelet)
    >>> plt.show()

    r   r               п)r#   Zlinspacepiexp)MwsZcompleterM   outputr   r   r   r	      s    @$ c           	      C   st   dt d| t jd   }|d }t d| | d d  }|d }d||  }t | d|  }|| | }|S )a  
    Return a Ricker wavelet, also known as the "Mexican hat wavelet".

    It models the function:

        ``A * (1 - (x/a)**2) * exp(-0.5*(x/a)**2)``,

    where ``A = 2/(sqrt(3*a)*(pi**0.25))``.

    Parameters
    ----------
    points : int
        Number of points in `vector`.
        Will be centered around 0.
    a : scalar
        Width parameter of the wavelet.

    Returns
    -------
    vector : (N,) ndarray
        Array of length `points` in shape of ricker curve.

    Examples
    --------
    >>> from scipy import signal
    >>> import matplotlib.pyplot as plt

    >>> points = 100
    >>> a = 4.0
    >>> vec2 = signal.ricker(points, a)
    >>> print(len(vec2))
    100
    >>> plt.plot(vec2)
    >>> plt.show()

    r   r   g      ?r   r[   r   )r#   r$   r^   rC   r_   )	ZpointsaAZwsqZvecZxsqmodgausstotalr   r   r   r
     s    %   c                 C   sd   t d| | d d  }|| }t d| | t d|d   t jd  }t d| | }|S )aR  
    Complex Morlet wavelet, designed to work with `cwt`.

    Returns the complete version of morlet wavelet, normalised
    according to `s`::

        exp(1j*w*x/s) * exp(-0.5*(x/s)**2) * pi**(-0.25) * sqrt(1/s)

    Parameters
    ----------
    M : int
        Length of the wavelet.
    s : float
        Width parameter of the wavelet.
    w : float, optional
        Omega0. Default is 5

    Returns
    -------
    morlet : (M,) ndarray

    See Also
    --------
    morlet : Implementation of Morlet wavelet, incompatible with `cwt`

    Notes
    -----

    .. versionadded:: 1.4.0

    This function was designed to work with `cwt`. Because `morlet2`
    returns an array of complex numbers, the `dtype` argument of `cwt`
    should be set to `complex128` for best results.

    Note the difference in implementation with `morlet`.
    The fundamental frequency of this wavelet in Hz is given by::

        f = w*fs / (2*s*np.pi)

    where ``fs`` is the sampling rate and `s` is the wavelet width parameter.
    Similarly we can get the wavelet width parameter at ``f``::

        s = w*fs / (2*f*np.pi)

    Examples
    --------
    >>> import numpy as np
    >>> from scipy import signal
    >>> import matplotlib.pyplot as plt

    >>> M = 100
    >>> s = 4.0
    >>> w = 2.0
    >>> wavelet = signal.morlet2(M, s, w)
    >>> plt.plot(abs(wavelet))
    >>> plt.show()

    This example shows basic use of `morlet2` with `cwt` in time-frequency
    analysis:

    >>> t, dt = np.linspace(0, 1, 200, retstep=True)
    >>> fs = 1/dt
    >>> w = 6.
    >>> sig = np.cos(2*np.pi*(50 + 10*t)*t) + np.sin(40*np.pi*t)
    >>> freq = np.linspace(1, fs/2, 100)
    >>> widths = w*fs / (2*freq*np.pi)
    >>> cwtm = signal.cwt(sig, signal.morlet2, widths, w=w)
    >>> plt.pcolormesh(t, freq, np.abs(cwtm), cmap='viridis', shading='gouraud')
    >>> plt.show()

    r   r[   r   r   r\   r]   r   )r#   rC   r_   r^   r$   )r`   rb   ra   rM   waveletrc   r   r   r   r   F  s
    H.c           
      K   s   |dkr6t |d|d f|jjdkr0t j}nt j}t jt|t| f|d}t|D ]N\}}t 	d| t| g}t 
|||f|ddd }	t| |	dd	||< qX|S )
a	  
    Continuous wavelet transform.

    Performs a continuous wavelet transform on `data`,
    using the `wavelet` function. A CWT performs a convolution
    with `data` using the `wavelet` function, which is characterized
    by a width parameter and length parameter. The `wavelet` function
    is allowed to be complex.

    Parameters
    ----------
    data : (N,) ndarray
        data on which to perform the transform.
    wavelet : function
        Wavelet function, which should take 2 arguments.
        The first argument is the number of points that the returned vector
        will have (len(wavelet(length,width)) == length).
        The second is a width parameter, defining the size of the wavelet
        (e.g. standard deviation of a gaussian). See `ricker`, which
        satisfies these requirements.
    widths : (M,) sequence
        Widths to use for transform.
    dtype : data-type, optional
        The desired data type of output. Defaults to ``float64`` if the
        output of `wavelet` is real and ``complex128`` if it is complex.

        .. versionadded:: 1.4.0

    kwargs
        Keyword arguments passed to wavelet function.

        .. versionadded:: 1.4.0

    Returns
    -------
    cwt: (M, N) ndarray
        Will have shape of (len(widths), len(data)).

    Notes
    -----

    .. versionadded:: 1.4.0

    For non-symmetric, complex-valued wavelets, the input signal is convolved
    with the time-reversed complex-conjugate of the wavelet data [1].

    ::

        length = min(10 * width[ii], len(data))
        cwt[ii,:] = signal.convolve(data, np.conj(wavelet(length, width[ii],
                                        **kwargs))[::-1], mode='same')

    References
    ----------
    .. [1] S. Mallat, "A Wavelet Tour of Signal Processing (3rd Edition)",
        Academic Press, 2009.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy import signal
    >>> import matplotlib.pyplot as plt
    >>> t = np.linspace(-1, 1, 200, endpoint=False)
    >>> sig  = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2)
    >>> widths = np.arange(1, 31)
    >>> cwtmatr = signal.cwt(sig, signal.ricker, widths)

    .. note:: For cwt matrix plotting it is advisable to flip the y-axis

    >>> cwtmatr_yflip = np.flipud(cwtmatr)
    >>> plt.imshow(cwtmatr_yflip, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto',
    ...            vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max())
    >>> plt.show()
    Nr   r   ZFDGr;   r   r!   Zsame)mode)r#   Zasarrayr<   charZ
complex128Zfloat64rB   r5   	enumerateminr'   r   )
datarj   widthsr<   kwargsrc   rQ   widthr7   Zwavelet_datar   r   r   r     s    L )r8   )rZ   r[   T)ri   )N)numpyr#   Zscipy.linalgr   Zscipy.specialr   Zscipy.signalr   __all__r   r   r   r	   r
   r   r   r   r   r   r   <module>   s   E
j
K/
O