if M < <NUM_LIT:1>:<EOL><INDENT>return np.array([])<EOL><DEDENT>if M == <NUM_LIT:1>:<EOL><INDENT>return np.ones(<NUM_LIT:1>, '<STR_LIT:d>')<EOL><DEDENT>odd = M % <NUM_LIT:2><EOL>if not sym and not odd:<EOL><INDENT>M = M + <NUM_LIT:1><EOL><DEDENT>n = np.arange(<NUM_LIT:0>, M)<EOL>fac = np.abs(n / (M - <NUM_LIT:1.0>) - <NUM_LIT:0.5>)<EOL>w = <NUM_LIT> - <NUM_LIT> * fac + <NUM_LIT> * np.cos(<NUM_LIT:2> * np.pi * fac)<EOL>if not sym and not odd:<EOL><INDENT>w = w[:-<NUM_LIT:1>]<EOL><DEDENT>return w<EOL>

Return a modified Bartlett-Hann window.

    Parameters
    ----------
    M : int
        Number of points in the output window. If zero or less, an empty
        array is returned.
    sym : bool, optional
        When True (default), generates a symmetric window, for use in filter
        design.
        When False, generates a periodic window, for use in spectral analysis.

    Returns
    -------
    w : ndarray
        The window, with the maximum value normalized to 1 (though the value 1
        does not appear if `M` is even and `sym` is True).

    Examples
    --------
    Plot the window and its frequency response:

    >>> from scipy import signal
    >>> from scipy.fftpack import fft, fftshift
    >>> import matplotlib.pyplot as plt

    >>> window = signal.barthann(51)
    >>> plt.plot(window)
    >>> plt.title("Bartlett-Hann window")
    >>> plt.ylabel("Amplitude")
    >>> plt.xlabel("Sample")

    >>> plt.figure()
    >>> A = fft(window, 2048) / (len(window)/2.0)
    >>> freq = np.linspace(-0.5, 0.5, len(A))
    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
    >>> plt.plot(freq, response)
    >>> plt.axis([-0.5, 0.5, -120, 0])
    >>> plt.title("Frequency response of the Bartlett-Hann window")
    >>> plt.ylabel("Normalized magnitude [dB]")
    >>> plt.xlabel("Normalized frequency [cycles per sample]")


<EOL>if M < <NUM_LIT:1>:<EOL><INDENT>return np.array([])<EOL><DEDENT>if M == <NUM_LIT:1>:<EOL><INDENT>return np.ones(<NUM_LIT:1>, '<STR_LIT:d>')<EOL><DEDENT>odd = M % <NUM_LIT:2><EOL>if not sym and not odd:<EOL><INDENT>M = M + <NUM_LIT:1><EOL><DEDENT>n = np.arange(<NUM_LIT:0>, M)<EOL>w = <NUM_LIT> - <NUM_LIT> * np.cos(<NUM_LIT> * np.pi * n / (M - <NUM_LIT:1>))<EOL>if not sym and not odd:<EOL><INDENT>w = w[:-<NUM_LIT:1>]<EOL><DEDENT>return w<EOL>

r"""Return a Hamming window.

    The Hamming window is a taper formed by using a raised cosine with
    non-zero endpoints, optimized to minimize the nearest side lobe.

    Parameters
    ----------
    M : int
        Number of points in the output window. If zero or less, an empty
        array is returned.
    sym : bool, optional
        When True (default), generates a symmetric window, for use in filter
        design.
        When False, generates a periodic window, for use in spectral analysis.

    Returns
    -------
    w : ndarray
        The window, with the maximum value normalized to 1 (though the value 1
        does not appear if `M` is even and `sym` is True).

    Notes
    -----
    The Hamming window is defined as

    .. math::  w(n) = 0.54 - 0.46 \cos\left(\frac{2\pi{n}}{M-1}\right)
               \qquad 0 \leq n \leq M-1

    The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and
    is described in Blackman and Tukey. It was recommended for smoothing the
    truncated autocovariance function in the time domain.
    Most references to the Hamming window come from the signal processing
    literature, where it is used as one of many windowing functions for
    smoothing values.  It is also known as an apodization (which means
    "removing the foot", i.e. smoothing discontinuities at the beginning
    and end of the sampled signal) or tapering function.

    References
    ----------
    .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
           spectra, Dover Publications, New York.
    .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
           University of Alberta Press, 1975, pp. 109-110.
    .. [3] Wikipedia, "Window function",
           http://en.wikipedia.org/wiki/Window_function
    .. [4] W.H. Press,  B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
           "Numerical Recipes", Cambridge University Press, 1986, page 425.

    Examples
    --------
    Plot the window and its frequency response:

    >>> from scipy import signal
    >>> from scipy.fftpack import fft, fftshift
    >>> import matplotlib.pyplot as plt

    >>> window = signal.hamming(51)
    >>> plt.plot(window)
    >>> plt.title("Hamming window")
    >>> plt.ylabel("Amplitude")
    >>> plt.xlabel("Sample")

    >>> plt.figure()
    >>> A = fft(window, 2048) / (len(window)/2.0)
    >>> freq = np.linspace(-0.5, 0.5, len(A))
    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
    >>> plt.plot(freq, response)
    >>> plt.axis([-0.5, 0.5, -120, 0])
    >>> plt.title("Frequency response of the Hamming window")
    >>> plt.ylabel("Normalized magnitude [dB]")
    >>> plt.xlabel("Normalized frequency [cycles per sample]")


<EOL>if M < <NUM_LIT:1>:<EOL><INDENT>return np.array([])<EOL><DEDENT>if M == <NUM_LIT:1>:<EOL><INDENT>return np.ones(<NUM_LIT:1>, '<STR_LIT:d>')<EOL><DEDENT>odd = M % <NUM_LIT:2><EOL>if not sym and not odd:<EOL><INDENT>M = M + <NUM_LIT:1><EOL><DEDENT>n = np.arange(<NUM_LIT:0>, M)<EOL>alpha = (M - <NUM_LIT:1>) / <NUM_LIT><EOL>w = (special.i0(beta * np.sqrt(<NUM_LIT:1> - ((n - alpha) / alpha) ** <NUM_LIT>)) /<EOL>special.i0(beta))<EOL>if not sym and not odd:<EOL><INDENT>w = w[:-<NUM_LIT:1>]<EOL><DEDENT>return w<EOL>

r"""Return a Kaiser window.

    The Kaiser window is a taper formed by using a Bessel function.

    Parameters
    ----------
    M : int
        Number of points in the output window. If zero or less, an empty
        array is returned.
    beta : float
        Shape parameter, determines trade-off between main-lobe width and
        side lobe level. As beta gets large, the window narrows.
    sym : bool, optional
        When True (default), generates a symmetric window, for use in filter
        design.
        When False, generates a periodic window, for use in spectral analysis.

    Returns
    -------
    w : ndarray
        The window, with the maximum value normalized to 1 (though the value 1
        does not appear if `M` is even and `sym` is True).

    Notes
    -----
    The Kaiser window is defined as

    .. math::  w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}}
               \right)/I_0(\beta)

    with

    .. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2},

    where :math:`I_0` is the modified zeroth-order Bessel function.

    The Kaiser was named for Jim Kaiser, who discovered a simple approximation
    to the DPSS window based on Bessel functions.
    The Kaiser window is a very good approximation to the Digital Prolate
    Spheroidal Sequence, or Slepian window, which is the transform which
    maximizes the energy in the main lobe of the window relative to total
    energy.

    The Kaiser can approximate many other windows by varying the beta
    parameter.

    ====  =======================
    beta  Window shape
    ====  =======================
    0     Rectangular
    5     Similar to a Hamming
    6     Similar to a Hann
    8.6   Similar to a Blackman
    ====  =======================

    A beta value of 14 is probably a good starting point. Note that as beta
    gets large, the window narrows, and so the number of samples needs to be
    large enough to sample the increasingly narrow spike, otherwise NaNs will
    get returned.

    Most references to the Kaiser window come from the signal processing
    literature, where it is used as one of many windowing functions for
    smoothing values.  It is also known as an apodization (which means
    "removing the foot", i.e. smoothing discontinuities at the beginning
    and end of the sampled signal) or tapering function.

    References
    ----------
    .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by
           digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285.
           John Wiley and Sons, New York, (1966).
    .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
           University of Alberta Press, 1975, pp. 177-178.
    .. [3] Wikipedia, "Window function",
           http://en.wikipedia.org/wiki/Window_function

    Examples
    --------
    Plot the window and its frequency response:

    >>> from scipy import signal
    >>> from scipy.fftpack import fft, fftshift
    >>> import matplotlib.pyplot as plt

    >>> window = signal.kaiser(51, beta=14)
    >>> plt.plot(window)
    >>> plt.title(r"Kaiser window ($\beta$=14)")
    >>> plt.ylabel("Amplitude")
    >>> plt.xlabel("Sample")

    >>> plt.figure()
    >>> A = fft(window, 2048) / (len(window)/2.0)
    >>> freq = np.linspace(-0.5, 0.5, len(A))
    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
    >>> plt.plot(freq, response)
    >>> plt.axis([-0.5, 0.5, -120, 0])
    >>> plt.title(r"Frequency response of the Kaiser window ($\beta$=14)")
    >>> plt.ylabel("Normalized magnitude [dB]")
    >>> plt.xlabel("Normalized frequency [cycles per sample]")


if M < <NUM_LIT:1>:<EOL><INDENT>return np.array([])<EOL><DEDENT>if M == <NUM_LIT:1>:<EOL><INDENT>return np.ones(<NUM_LIT:1>, '<STR_LIT:d>')<EOL><DEDENT>odd = M % <NUM_LIT:2><EOL>if not sym and not odd:<EOL><INDENT>M = M + <NUM_LIT:1><EOL><DEDENT>n = np.arange(<NUM_LIT:0>, M) - (M - <NUM_LIT:1.0>) / <NUM_LIT><EOL>sig2 = <NUM_LIT:2> * std * std<EOL>w = np.exp(-n ** <NUM_LIT:2> / sig2)<EOL>if not sym and not odd:<EOL><INDENT>w = w[:-<NUM_LIT:1>]<EOL><DEDENT>return w<EOL>

r"""Return a Gaussian window.

    Parameters
    ----------
    M : int
        Number of points in the output window. If zero or less, an empty
        array is returned.
    std : float
        The standard deviation, sigma.
    sym : bool, optional
        When True (default), generates a symmetric window, for use in filter
        design.
        When False, generates a periodic window, for use in spectral analysis.

    Returns
    -------
    w : ndarray
        The window, with the maximum value normalized to 1 (though the value 1
        does not appear if `M` is even and `sym` is True).

    Notes
    -----
    The Gaussian window is defined as

    .. math::  w(n) = e^{ -\frac{1}{2}\left(\frac{n}{\sigma}\right)^2 }

    Examples
    --------
    Plot the window and its frequency response:

    >>> from scipy import signal
    >>> from scipy.fftpack import fft, fftshift
    >>> import matplotlib.pyplot as plt

    >>> window = signal.gaussian(51, std=7)
    >>> plt.plot(window)
    >>> plt.title(r"Gaussian window ($\sigma$=7)")
    >>> plt.ylabel("Amplitude")
    >>> plt.xlabel("Sample")

    >>> plt.figure()
    >>> A = fft(window, 2048) / (len(window)/2.0)
    >>> freq = np.linspace(-0.5, 0.5, len(A))
    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
    >>> plt.plot(freq, response)
    >>> plt.axis([-0.5, 0.5, -120, 0])
    >>> plt.title(r"Frequency response of the Gaussian window ($\sigma$=7)")
    >>> plt.ylabel("Normalized magnitude [dB]")
    >>> plt.xlabel("Normalized frequency [cycles per sample]")


def general_gaussian(M, p, sig, sym=True):

if M < <NUM_LIT:1>:<EOL><INDENT>return np.array([])<EOL><DEDENT>if M == <NUM_LIT:1>:<EOL><INDENT>return np.ones(<NUM_LIT:1>, '<STR_LIT:d>')<EOL><DEDENT>odd = M % <NUM_LIT:2><EOL>if not sym and not odd:<EOL><INDENT>M = M + <NUM_LIT:1><EOL><DEDENT>n = np.arange(<NUM_LIT:0>, M) - (M - <NUM_LIT:1.0>) / <NUM_LIT><EOL>w = np.exp(-<NUM_LIT:0.5> * np.abs(n / sig) ** (<NUM_LIT:2> * p))<EOL>if not sym and not odd:<EOL><INDENT>w = w[:-<NUM_LIT:1>]<EOL><DEDENT>return w<EOL>

r"""Return a window with a generalized Gaussian shape.

    Parameters
    ----------
    M : int
        Number of points in the output window. If zero or less, an empty
        array is returned.
    p : float
        Shape parameter.  p = 1 is identical to `gaussian`, p = 0.5 is
        the same shape as the Laplace distribution.
    sig : float
        The standard deviation, sigma.
    sym : bool, optional
        When True (default), generates a symmetric window, for use in filter
        design.
        When False, generates a periodic window, for use in spectral analysis.

    Returns
    -------
    w : ndarray
        The window, with the maximum value normalized to 1 (though the value 1
        does not appear if `M` is even and `sym` is True).

    Notes
    -----
    The generalized Gaussian window is defined as

    .. math::  w(n) = e^{ -\frac{1}{2}\left|\frac{n}{\sigma}\right|^{2p} }

    the half-power point is at

    .. math::  (2 \log(2))^{1/(2 p)} \sigma

    Examples
    --------
    Plot the window and its frequency response:

    >>> from scipy import signal
    >>> from scipy.fftpack import fft, fftshift
    >>> import matplotlib.pyplot as plt

    >>> window = signal.general_gaussian(51, p=1.5, sig=7)
    >>> plt.plot(window)
    >>> plt.title(r"Generalized Gaussian window (p=1.5, $\sigma$=7)")
    >>> plt.ylabel("Amplitude")
    >>> plt.xlabel("Sample")

    >>> plt.figure()
    >>> A = fft(window, 2048) / (len(window)/2.0)
    >>> freq = np.linspace(-0.5, 0.5, len(A))
    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
    >>> plt.plot(freq, response)
    >>> plt.axis([-0.5, 0.5, -120, 0])
    >>> plt.title(r"Freq. resp. of the gen. Gaussian window (p=1.5, $\sigma$=7)")
    >>> plt.ylabel("Normalized magnitude [dB]")
    >>> plt.xlabel("Normalized frequency [cycles per sample]")


if np.abs(at) < <NUM_LIT>:<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if M < <NUM_LIT:1>:<EOL><INDENT>return np.array([])<EOL><DEDENT>if M == <NUM_LIT:1>:<EOL><INDENT>return np.ones(<NUM_LIT:1>, '<STR_LIT:d>')<EOL><DEDENT>odd = M % <NUM_LIT:2><EOL>if not sym and not odd:<EOL><INDENT>M = M + <NUM_LIT:1><EOL><DEDENT>order = M - <NUM_LIT:1.0><EOL>beta = np.cosh(<NUM_LIT:1.0> / order * np.arccosh(<NUM_LIT:10> ** (np.abs(at) / <NUM_LIT>)))<EOL>k = np.r_[<NUM_LIT:0>:M] * <NUM_LIT:1.0><EOL>x = beta * np.cos(np.pi * k / M)<EOL>p = np.zeros(x.shape)<EOL>p[x > <NUM_LIT:1>] = np.cosh(order * np.arccosh(x[x > <NUM_LIT:1>]))<EOL>p[x < -<NUM_LIT:1>] = (<NUM_LIT:1> - <NUM_LIT:2> * (order % <NUM_LIT:2>)) * np.cosh(order * np.arccosh(-x[x < -<NUM_LIT:1>]))<EOL>p[np.abs(x) <= <NUM_LIT:1>] = np.cos(order * np.arccos(x[np.abs(x) <= <NUM_LIT:1>]))<EOL>if M % <NUM_LIT:2>:<EOL><INDENT>w = np.real(fft(p))<EOL>n = (M + <NUM_LIT:1>) // <NUM_LIT:2><EOL>w = w[:n]<EOL>w = np.concatenate((w[n - <NUM_LIT:1>:<NUM_LIT:0>:-<NUM_LIT:1>], w))<EOL><DEDENT>else:<EOL><INDENT>p = p * np.exp(<NUM_LIT> * np.pi / M * np.r_[<NUM_LIT:0>:M])<EOL>w = np.real(fft(p))<EOL>n = M // <NUM_LIT:2> + <NUM_LIT:1><EOL>w = np.concatenate((w[n - <NUM_LIT:1>:<NUM_LIT:0>:-<NUM_LIT:1>], w[<NUM_LIT:1>:n]))<EOL><DEDENT>w = w / max(w)<EOL>if not sym and not odd:<EOL><INDENT>w = w[:-<NUM_LIT:1>]<EOL><DEDENT>return w<EOL>

r"""Return a Dolph-Chebyshev window.

    Parameters
    ----------
    M : int
        Number of points in the output window. If zero or less, an empty
        array is returned.
    at : float
        Attenuation (in dB).
    sym : bool, optional
        When True (default), generates a symmetric window, for use in filter
        design.
        When False, generates a periodic window, for use in spectral analysis.

    Returns
    -------
    w : ndarray
        The window, with the maximum value always normalized to 1

    Notes
    -----
    This window optimizes for the narrowest main lobe width for a given order
    `M` and sidelobe equiripple attenuation `at`, using Chebyshev
    polynomials.  It was originally developed by Dolph to optimize the
    directionality of radio antenna arrays.

    Unlike most windows, the Dolph-Chebyshev is defined in terms of its
    frequency response:

    .. math:: W(k) = \frac
              {\cos\{M \cos^{-1}[\beta \cos(\frac{\pi k}{M})]\}}
              {\cosh[M \cosh^{-1}(\beta)]}

    where

    .. math:: \beta = \cosh \left [\frac{1}{M}
              \cosh^{-1}(10^\frac{A}{20}) \right ]

    and 0 <= abs(k) <= M-1. A is the attenuation in decibels (`at`).

    The time domain window is then generated using the IFFT, so
    power-of-two `M` are the fastest to generate, and prime number `M` are
    the slowest.

    The equiripple condition in the frequency domain creates impulses in the
    time domain, which appear at the ends of the window.

    References
    ----------
    .. [1] C. Dolph, "A current distribution for broadside arrays which
           optimizes the relationship between beam width and side-lobe level",
           Proceedings of the IEEE, Vol. 34, Issue 6
    .. [2] Peter Lynch, "The Dolph-Chebyshev Window: A Simple Optimal Filter",
           American Meteorological Society (April 1997)
           http://mathsci.ucd.ie/~plynch/Publications/Dolph.pdf
    .. [3] F. J. Harris, "On the use of windows for harmonic analysis with the
           discrete Fourier transforms", Proceedings of the IEEE, Vol. 66,
           No. 1, January 1978

    Examples
    --------
    Plot the window and its frequency response:

    >>> from scipy import signal
    >>> from scipy.fftpack import fft, fftshift
    >>> import matplotlib.pyplot as plt

    >>> window = signal.chebwin(51, at=100)
    >>> plt.plot(window)
    >>> plt.title("Dolph-Chebyshev window (100 dB)")
    >>> plt.ylabel("Amplitude")
    >>> plt.xlabel("Sample")

    >>> plt.figure()
    >>> A = fft(window, 2048) / (len(window)/2.0)
    >>> freq = np.linspace(-0.5, 0.5, len(A))
    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
    >>> plt.plot(freq, response)
    >>> plt.axis([-0.5, 0.5, -120, 0])
    >>> plt.title("Frequency response of the Dolph-Chebyshev window (100 dB)")
    >>> plt.ylabel("Normalized magnitude [dB]")
    >>> plt.xlabel("Normalized frequency [cycles per sample]")


if (M * width > <NUM_LIT>):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if M < <NUM_LIT:1>:<EOL><INDENT>return np.array([])<EOL><DEDENT>if M == <NUM_LIT:1>:<EOL><INDENT>return np.ones(<NUM_LIT:1>, '<STR_LIT:d>')<EOL><DEDENT>odd = M % <NUM_LIT:2><EOL>if not sym and not odd:<EOL><INDENT>M = M + <NUM_LIT:1><EOL><DEDENT>twoF = width / <NUM_LIT><EOL>alpha = (M - <NUM_LIT:1>) / <NUM_LIT><EOL>m = np.arange(<NUM_LIT:0>, M) - alpha<EOL>n = m[:, np.newaxis]<EOL>k = m[np.newaxis, :]<EOL>AF = twoF * special.sinc(twoF * (n - k))<EOL>[lam, vec] = linalg.eig(AF)<EOL>ind = np.argmax(abs(lam), axis=-<NUM_LIT:1>)<EOL>w = np.abs(vec[:, ind])<EOL>w = w / max(w)<EOL>if not sym and not odd:<EOL><INDENT>w = w[:-<NUM_LIT:1>]<EOL><DEDENT>return w<EOL>

Return a digital Slepian (DPSS) window.

    Used to maximize the energy concentration in the main lobe.  Also called
    the digital prolate spheroidal sequence (DPSS).

    Parameters
    ----------
    M : int
        Number of points in the output window. If zero or less, an empty
        array is returned.
    width : float
        Bandwidth
    sym : bool, optional
        When True (default), generates a symmetric window, for use in filter
        design.
        When False, generates a periodic window, for use in spectral analysis.

    Returns
    -------
    w : ndarray
        The window, with the maximum value always normalized to 1

    Examples
    --------
    Plot the window and its frequency response:

    >>> from scipy import signal
    >>> from scipy.fftpack import fft, fftshift
    >>> import matplotlib.pyplot as plt

    >>> window = signal.slepian(51, width=0.3)
    >>> plt.plot(window)
    >>> plt.title("Slepian (DPSS) window (BW=0.3)")
    >>> plt.ylabel("Amplitude")
    >>> plt.xlabel("Sample")

    >>> plt.figure()
    >>> A = fft(window, 2048) / (len(window)/2.0)
    >>> freq = np.linspace(-0.5, 0.5, len(A))
    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
    >>> plt.plot(freq, response)
    >>> plt.axis([-0.5, 0.5, -120, 0])
    >>> plt.title("Frequency response of the Slepian window (BW=0.3)")
    >>> plt.ylabel("Normalized magnitude [dB]")
    >>> plt.xlabel("Normalized frequency [cycles per sample]")


if M < <NUM_LIT:1>:<EOL><INDENT>return np.array([])<EOL><DEDENT>if M == <NUM_LIT:1>:<EOL><INDENT>return np.ones(<NUM_LIT:1>, '<STR_LIT:d>')<EOL><DEDENT>odd = M % <NUM_LIT:2><EOL>if not sym and not odd:<EOL><INDENT>M = M + <NUM_LIT:1><EOL><DEDENT>w = np.sin(np.pi / M * (np.arange(<NUM_LIT:0>, M) + <NUM_LIT>))<EOL>if not sym and not odd:<EOL><INDENT>w = w[:-<NUM_LIT:1>]<EOL><DEDENT>return w<EOL>

Return a window with a simple cosine shape.

    Parameters
    ----------
    M : int
        Number of points in the output window. If zero or less, an empty
        array is returned.
    sym : bool, optional
        When True (default), generates a symmetric window, for use in filter
        design.
        When False, generates a periodic window, for use in spectral analysis.

    Returns
    -------
    w : ndarray
        The window, with the maximum value normalized to 1 (though the value 1
        does not appear if `M` is even and `sym` is True).

    Notes
    -----

    .. versionadded:: 0.13.0

    Examples
    --------
    Plot the window and its frequency response:

    >>> from scipy import signal
    >>> from scipy.fftpack import fft, fftshift
    >>> import matplotlib.pyplot as plt

    >>> window = signal.cosine(51)
    >>> plt.plot(window)
    >>> plt.title("Cosine window")
    >>> plt.ylabel("Amplitude")
    >>> plt.xlabel("Sample")

    >>> plt.figure()
    >>> A = fft(window, 2048) / (len(window)/2.0)
    >>> freq = np.linspace(-0.5, 0.5, len(A))
    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
    >>> plt.plot(freq, response)
    >>> plt.axis([-0.5, 0.5, -120, 0])
    >>> plt.title("Frequency response of the cosine window")
    >>> plt.ylabel("Normalized magnitude [dB]")
    >>> plt.xlabel("Normalized frequency [cycles per sample]")
    >>> plt.show()


def get_window(window, Nx, fftbins=True):

sym = not fftbins<EOL>try:<EOL><INDENT>beta = float(window)<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>args = ()<EOL>if isinstance(window, tuple):<EOL><INDENT>winstr = window[<NUM_LIT:0>]<EOL>if len(window) > <NUM_LIT:1>:<EOL><INDENT>args = window[<NUM_LIT:1>:]<EOL><DEDENT><DEDENT>elif isinstance(window, string_types):<EOL><INDENT>if window in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>" + window + "<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>winstr = window<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % str(type(window)))<EOL><DEDENT>if winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = blackman<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = triang<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = hamming<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = bartlett<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = hann<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = blackmanharris<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = parzen<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = bohman<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = nuttall<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = barthann<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = flattop<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = kaiser<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = gaussian<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = general_gaussian<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = boxcar<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = slepian<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = cosine<EOL><DEDENT>elif winstr in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>winfunc = chebwin<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>params = (Nx,) + args + (sym,)<EOL><DEDENT>else:<EOL><INDENT>winfunc = kaiser<EOL>params = (Nx, beta, sym)<EOL><DEDENT>return winfunc(*params)<EOL>

Return a window.

Parameters
----------
window : string, float, or tuple
    The type of window to create. See below for more details.
Nx : int
    The number of samples in the window.
fftbins : bool, optional
    If True, create a "periodic" window ready to use with ifftshift
    and be multiplied by the result of an fft (SEE ALSO fftfreq).

Returns
-------
get_window : ndarray
    Returns a window of length `Nx` and type `window`

Notes
-----
Window types:

    boxcar, triang, blackman, hamming, hann, bartlett, flattop,
    parzen, bohman, blackmanharris, nuttall, barthann,
    kaiser (needs beta), gaussian (needs std),
    general_gaussian (needs power, width),
    slepian (needs width), chebwin (needs attenuation)

If the window requires no parameters, then `window` can be a string.

If the window requires parameters, then `window` must be a tuple
with the first argument the string name of the window, and the next
arguments the needed parameters.

If `window` is a floating point number, it is interpreted as the beta
parameter of the kaiser window.

Each of the window types listed above is also the name of
a function that can be called directly to create a window of
that type.

Examples
--------
>>> from scipy import signal
>>> signal.get_window('triang', 7)
array([ 0.25,  0.5 ,  0.75,  1.  ,  0.75,  0.5 ,  0.25])
>>> signal.get_window(('kaiser', 4.0), 9)
array([ 0.08848053,  0.32578323,  0.63343178,  0.89640418,  1.        ,
        0.89640418,  0.63343178,  0.32578323,  0.08848053])
>>> signal.get_window(4.0, 9)
array([ 0.08848053,  0.32578323,  0.63343178,  0.89640418,  1.        ,
        0.89640418,  0.63343178,  0.32578323,  0.08848053])


t, w = asarray(t), asarray(width)<EOL>w = asarray(w + (t - t))<EOL>t = asarray(t + (w - w))<EOL>if t.dtype.char in ['<STR_LIT>']:<EOL><INDENT>ytype = t.dtype.char<EOL><DEDENT>else:<EOL><INDENT>ytype = '<STR_LIT:d>'<EOL><DEDENT>y = zeros(t.shape, ytype)<EOL>mask1 = (w > <NUM_LIT:1>) | (w < <NUM_LIT:0>)<EOL>place(y, mask1, nan)<EOL>tmod = mod(t, <NUM_LIT:2> * pi)<EOL>mask2 = (<NUM_LIT:1> - mask1) & (tmod < w * <NUM_LIT:2> * pi)<EOL>tsub = extract(mask2, tmod)<EOL>wsub = extract(mask2, w)<EOL>place(y, mask2, tsub / (pi * wsub) - <NUM_LIT:1>)<EOL>mask3 = (<NUM_LIT:1> - mask1) & (<NUM_LIT:1> - mask2)<EOL>tsub = extract(mask3, tmod)<EOL>wsub = extract(mask3, w)<EOL>place(y, mask3, (pi * (wsub + <NUM_LIT:1>) - tsub) / (pi * (<NUM_LIT:1> - wsub)))<EOL>return y<EOL>

Return a periodic sawtooth or triangle waveform.

The sawtooth waveform has a period ``2*pi``, rises from -1 to 1 on the
interval 0 to ``width*2*pi``, then drops from 1 to -1 on the interval
``width*2*pi`` to ``2*pi``. `width` must be in the interval [0, 1].

Note that this is not band-limited.  It produces an infinite number
of harmonics, which are aliased back and forth across the frequency
spectrum.

Parameters
----------
t : array_like
    Time.
width : array_like, optional
    Width of the rising ramp as a proportion of the total cycle.
    Default is 1, producing a rising ramp, while 0 produces a falling
    ramp.  `t` = 0.5 produces a triangle wave.
    If an array, causes wave shape to change over time, and must be the
    same length as t.

Returns
-------
y : ndarray
    Output array containing the sawtooth waveform.

Examples
--------
A 5 Hz waveform sampled at 500 Hz for 1 second:

>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(0, 1, 500)
>>> plt.plot(t, signal.sawtooth(2 * np.pi * 5 * t))


t, w = asarray(t), asarray(duty)<EOL>w = asarray(w + (t - t))<EOL>t = asarray(t + (w - w))<EOL>if t.dtype.char in ['<STR_LIT>']:<EOL><INDENT>ytype = t.dtype.char<EOL><DEDENT>else:<EOL><INDENT>ytype = '<STR_LIT:d>'<EOL><DEDENT>y = zeros(t.shape, ytype)<EOL>mask1 = (w > <NUM_LIT:1>) | (w < <NUM_LIT:0>)<EOL>place(y, mask1, nan)<EOL>tmod = mod(t, <NUM_LIT:2> * pi)<EOL>mask2 = (<NUM_LIT:1> - mask1) & (tmod < w * <NUM_LIT:2> * pi)<EOL>place(y, mask2, <NUM_LIT:1>)<EOL>mask3 = (<NUM_LIT:1> - mask1) & (<NUM_LIT:1> - mask2)<EOL>place(y, mask3, -<NUM_LIT:1>)<EOL>return y<EOL>

Return a periodic square-wave waveform.

The square wave has a period ``2*pi``, has value +1 from 0 to
``2*pi*duty`` and -1 from ``2*pi*duty`` to ``2*pi``. `duty` must be in
the interval [0,1].

Note that this is not band-limited.  It produces an infinite number
of harmonics, which are aliased back and forth across the frequency
spectrum.

Parameters
----------
t : array_like
    The input time array.
duty : array_like, optional
    Duty cycle.  Default is 0.5 (50% duty cycle).
    If an array, causes wave shape to change over time, and must be the
    same length as t.

Returns
-------
y : ndarray
    Output array containing the square waveform.

Examples
--------
A 5 Hz waveform sampled at 500 Hz for 1 second:

>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(0, 1, 500, endpoint=False)
>>> plt.plot(t, signal.square(2 * np.pi * 5 * t))
>>> plt.ylim(-2, 2)

A pulse-width modulated sine wave:

>>> plt.figure()
>>> sig = np.sin(2 * np.pi * t)
>>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)
>>> plt.subplot(2, 1, 1)
>>> plt.plot(t, sig)
>>> plt.subplot(2, 1, 2)
>>> plt.plot(t, pwm)
>>> plt.ylim(-1.5, 1.5)


def gausspulse(t, fc=<NUM_LIT:1000>, bw=<NUM_LIT:0.5>, bwr=-<NUM_LIT:6>, tpr=-<NUM_LIT>, retquad=False,<EOL>retenv=False):

if fc < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % fc)<EOL><DEDENT>if bw <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % bw)<EOL><DEDENT>if bwr >= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % bwr)<EOL><DEDENT>ref = pow(<NUM_LIT>, bwr / <NUM_LIT>)<EOL>a = -(pi * fc * bw) ** <NUM_LIT:2> / (<NUM_LIT> * log(ref))<EOL>if t == '<STR_LIT>':  <EOL><INDENT>if tpr >= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>tref = pow(<NUM_LIT>, tpr / <NUM_LIT>)<EOL>return sqrt(-log(tref) / a)<EOL><DEDENT>yenv = exp(-a * t * t)<EOL>yI = yenv * cos(<NUM_LIT:2> * pi * fc * t)<EOL>yQ = yenv * sin(<NUM_LIT:2> * pi * fc * t)<EOL>if not retquad and not retenv:<EOL><INDENT>return yI<EOL><DEDENT>if not retquad and retenv:<EOL><INDENT>return yI, yenv<EOL><DEDENT>if retquad and not retenv:<EOL><INDENT>return yI, yQ<EOL><DEDENT>if retquad and retenv:<EOL><INDENT>return yI, yQ, yenv<EOL><DEDENT>

Return a Gaussian modulated sinusoid:

    ``exp(-a t^2) exp(1j*2*pi*fc*t).``

If `retquad` is True, then return the real and imaginary parts
(in-phase and quadrature).
If `retenv` is True, then return the envelope (unmodulated signal).
Otherwise, return the real part of the modulated sinusoid.

Parameters
----------
t : ndarray or the string 'cutoff'
    Input array.
fc : int, optional
    Center frequency (e.g. Hz).  Default is 1000.
bw : float, optional
    Fractional bandwidth in frequency domain of pulse (e.g. Hz).
    Default is 0.5.
bwr : float, optional
    Reference level at which fractional bandwidth is calculated (dB).
    Default is -6.
tpr : float, optional
    If `t` is 'cutoff', then the function returns the cutoff
    time for when the pulse amplitude falls below `tpr` (in dB).
    Default is -60.
retquad : bool, optional
    If True, return the quadrature (imaginary) as well as the real part
    of the signal.  Default is False.
retenv : bool, optional
    If True, return the envelope of the signal.  Default is False.

Returns
-------
yI : ndarray
    Real part of signal.  Always returned.
yQ : ndarray
    Imaginary part of signal.  Only returned if `retquad` is True.
yenv : ndarray
    Envelope of signal.  Only returned if `retenv` is True.

See Also
--------
scipy.signal.morlet

Examples
--------
Plot real component, imaginary component, and envelope for a 5 Hz pulse,
sampled at 100 Hz for 2 seconds:

>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(-1, 1, 2 * 100, endpoint=False)
>>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True)
>>> plt.plot(t, i, t, q, t, e, '--')


def chirp(t, f0, t1, f1, method='<STR_LIT>', phi=<NUM_LIT:0>, vertex_zero=True):

<EOL>phase = _chirp_phase(t, f0, t1, f1, method, vertex_zero)<EOL>phi *= pi / <NUM_LIT><EOL>return cos(phase + phi)<EOL>

Frequency-swept cosine generator.

    In the following, 'Hz' should be interpreted as 'cycles per unit';
    there is no requirement here that the unit is one second.  The
    important distinction is that the units of rotation are cycles, not
    radians. Likewise, `t` could be a measurement of space instead of time.

    Parameters
    ----------
    t : array_like
        Times at which to evaluate the waveform.
    f0 : float
        Frequency (e.g. Hz) at time t=0.
    t1 : float
        Time at which `f1` is specified.
    f1 : float
        Frequency (e.g. Hz) of the waveform at time `t1`.
    method : {'linear', 'quadratic', 'logarithmic', 'hyperbolic'}, optional
        Kind of frequency sweep.  If not given, `linear` is assumed.  See
        Notes below for more details.
    phi : float, optional
        Phase offset, in degrees. Default is 0.
    vertex_zero : bool, optional
        This parameter is only used when `method` is 'quadratic'.
        It determines whether the vertex of the parabola that is the graph
        of the frequency is at t=0 or t=t1.

    Returns
    -------
    y : ndarray
        A numpy array containing the signal evaluated at `t` with the
        requested time-varying frequency.  More precisely, the function
        returns ``cos(phase + (pi/180)*phi)`` where `phase` is the integral
        (from 0 to `t`) of ``2*pi*f(t)``. ``f(t)`` is defined below.

    See Also
    --------
    sweep_poly

    Notes
    -----
    There are four options for the `method`.  The following formulas give
    the instantaneous frequency (in Hz) of the signal generated by
    `chirp()`.  For convenience, the shorter names shown below may also be
    used.

    linear, lin, li:

        ``f(t) = f0 + (f1 - f0) * t / t1``

    quadratic, quad, q:

        The graph of the frequency f(t) is a parabola through (0, f0) and
        (t1, f1).  By default, the vertex of the parabola is at (0, f0).
        If `vertex_zero` is False, then the vertex is at (t1, f1).  The
        formula is:

        if vertex_zero is True:

            ``f(t) = f0 + (f1 - f0) * t**2 / t1**2``

        else:

            ``f(t) = f1 - (f1 - f0) * (t1 - t)**2 / t1**2``

        To use a more general quadratic function, or an arbitrary
        polynomial, use the function `scipy.signal.waveforms.sweep_poly`.

    logarithmic, log, lo:

        ``f(t) = f0 * (f1/f0)**(t/t1)``

        f0 and f1 must be nonzero and have the same sign.

        This signal is also known as a geometric or exponential chirp.

    hyperbolic, hyp:

        ``f(t) = f0*f1*t1 / ((f0 - f1)*t + f1*t1)``

        f0 and f1 must be nonzero.


def _chirp_phase(t, f0, t1, f1, method='<STR_LIT>', vertex_zero=True):

t = asarray(t)<EOL>f0 = float(f0)<EOL>t1 = float(t1)<EOL>f1 = float(f1)<EOL>if method in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>beta = (f1 - f0) / t1<EOL>phase = <NUM_LIT:2> * pi * (f0 * t + <NUM_LIT:0.5> * beta * t * t)<EOL><DEDENT>elif method in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT:q>']:<EOL><INDENT>beta = (f1 - f0) / (t1 ** <NUM_LIT:2>)<EOL>if vertex_zero:<EOL><INDENT>phase = <NUM_LIT:2> * pi * (f0 * t + beta * t ** <NUM_LIT:3> / <NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>phase = <NUM_LIT:2> * pi * (f1 * t + beta * ((t1 - t) ** <NUM_LIT:3> - t1 ** <NUM_LIT:3>) / <NUM_LIT:3>)<EOL><DEDENT><DEDENT>elif method in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if f0 * f1 <= <NUM_LIT:0.0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if f0 == f1:<EOL><INDENT>phase = <NUM_LIT:2> * pi * f0 * t<EOL><DEDENT>else:<EOL><INDENT>beta = t1 / log(f1 / f0)<EOL>phase = <NUM_LIT:2> * pi * beta * f0 * (pow(f1 / f0, t / t1) - <NUM_LIT:1.0>)<EOL><DEDENT><DEDENT>elif method in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if f0 == <NUM_LIT:0> or f1 == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if f0 == f1:<EOL><INDENT>phase = <NUM_LIT:2> * pi * f0 * t<EOL><DEDENT>else:<EOL><INDENT>sing = -f1 * t1 / (f0 - f1)<EOL>phase = <NUM_LIT:2> * pi * (-sing * f0) * log(np.abs(<NUM_LIT:1> - t/sing))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% method)<EOL><DEDENT>return phase<EOL>

Calculate the phase used by chirp_phase to generate its output.

See `chirp_phase` for a description of the arguments.


def sweep_poly(t, poly, phi=<NUM_LIT:0>):

<EOL>phase = _sweep_poly_phase(t, poly)<EOL>phi *= pi / <NUM_LIT><EOL>return cos(phase + phi)<EOL>

Frequency-swept cosine generator, with a time-dependent frequency.

This function generates a sinusoidal function whose instantaneous
frequency varies with time.  The frequency at time `t` is given by
the polynomial `poly`.

Parameters
----------
t : ndarray
    Times at which to evaluate the waveform.
poly : 1-D array-like or instance of numpy.poly1d
    The desired frequency expressed as a polynomial.  If `poly` is
    a list or ndarray of length n, then the elements of `poly` are
    the coefficients of the polynomial, and the instantaneous
    frequency is

      ``f(t) = poly[0]*t**(n-1) + poly[1]*t**(n-2) + ... + poly[n-1]``

    If `poly` is an instance of numpy.poly1d, then the
    instantaneous frequency is

      ``f(t) = poly(t)``

phi : float, optional
    Phase offset, in degrees, Default: 0.

Returns
-------
sweep_poly : ndarray
    A numpy array containing the signal evaluated at `t` with the
    requested time-varying frequency.  More precisely, the function
    returns ``cos(phase + (pi/180)*phi)``, where `phase` is the integral
    (from 0 to t) of ``2 * pi * f(t)``; ``f(t)`` is defined above.

See Also
--------
chirp

Notes
-----
.. versionadded:: 0.8.0

If `poly` is a list or ndarray of length `n`, then the elements of
`poly` are the coefficients of the polynomial, and the instantaneous
frequency is:

    ``f(t) = poly[0]*t**(n-1) + poly[1]*t**(n-2) + ... + poly[n-1]``

If `poly` is an instance of `numpy.poly1d`, then the instantaneous
frequency is:

      ``f(t) = poly(t)``

Finally, the output `s` is:

    ``cos(phase + (pi/180)*phi)``

where `phase` is the integral from 0 to `t` of ``2 * pi * f(t)``,
``f(t)`` as defined above.


<EOL>intpoly = polyint(poly)<EOL>phase = <NUM_LIT:2> * pi * polyval(intpoly, t)<EOL>return phase<EOL>

Calculate the phase used by sweep_poly to generate its output.

See `sweep_poly` for a description of the arguments.


intype = Iin.dtype.char<EOL>hcol = array([<NUM_LIT:1.0>, <NUM_LIT>, <NUM_LIT:1.0>], '<STR_LIT:f>') / <NUM_LIT><EOL>if intype in ['<STR_LIT:F>', '<STR_LIT:D>']:<EOL><INDENT>Iin = Iin.astype('<STR_LIT:F>')<EOL>ckr = cspline2d(Iin.real, lmbda)<EOL>cki = cspline2d(Iin.imag, lmbda)<EOL>outr = sepfir2d(ckr, hcol, hcol)<EOL>outi = sepfir2d(cki, hcol, hcol)<EOL>out = (outr + <NUM_LIT> * outi).astype(intype)<EOL><DEDENT>elif intype in ['<STR_LIT:f>', '<STR_LIT:d>']:<EOL><INDENT>ckr = cspline2d(Iin, lmbda)<EOL>out = sepfir2d(ckr, hcol, hcol)<EOL>out = out.astype(intype)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return out<EOL>

Smoothing spline (cubic) filtering of a rank-2 array.

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


try:<EOL><INDENT>return _splinefunc_cache[order]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>def condfuncgen(num, val1, val2):<EOL><INDENT>if num == <NUM_LIT:0>:<EOL><INDENT>return lambda x: logical_and(less_equal(x, val1),<EOL>greater_equal(x, val2))<EOL><DEDENT>elif num == <NUM_LIT:2>:<EOL><INDENT>return lambda x: less_equal(x, val2)<EOL><DEDENT>else:<EOL><INDENT>return lambda x: logical_and(less(x, val1),<EOL>greater_equal(x, val2))<EOL><DEDENT><DEDENT>last = order // <NUM_LIT:2> + <NUM_LIT:2><EOL>if order % <NUM_LIT:2>:<EOL><INDENT>startbound = -<NUM_LIT:1.0><EOL><DEDENT>else:<EOL><INDENT>startbound = -<NUM_LIT:0.5><EOL><DEDENT>condfuncs = [condfuncgen(<NUM_LIT:0>, <NUM_LIT:0>, startbound)]<EOL>bound = startbound<EOL>for num in xrange(<NUM_LIT:1>, last - <NUM_LIT:1>):<EOL><INDENT>condfuncs.append(condfuncgen(<NUM_LIT:1>, bound, bound - <NUM_LIT:1>))<EOL>bound = bound - <NUM_LIT:1><EOL><DEDENT>condfuncs.append(condfuncgen(<NUM_LIT:2>, <NUM_LIT:0>, -(order + <NUM_LIT:1>) / <NUM_LIT>))<EOL>fval = factorial(order)<EOL>def piecefuncgen(num):<EOL><INDENT>Mk = order // <NUM_LIT:2> - num<EOL>if (Mk < <NUM_LIT:0>):<EOL><INDENT>return <NUM_LIT:0>  <EOL><DEDENT>coeffs = [(<NUM_LIT:1> - <NUM_LIT:2> * (k % <NUM_LIT:2>)) * float(comb(order + <NUM_LIT:1>, k, exact=<NUM_LIT:1>)) / fval<EOL>for k in xrange(Mk + <NUM_LIT:1>)]<EOL>shifts = [-bound - k for k in xrange(Mk + <NUM_LIT:1>)]<EOL>def thefunc(x):<EOL><INDENT>res = <NUM_LIT:0.0><EOL>for k in range(Mk + <NUM_LIT:1>):<EOL><INDENT>res += coeffs[k] * (x + shifts[k]) ** order<EOL><DEDENT>return res<EOL><DEDENT>return thefunc<EOL><DEDENT>funclist = [piecefuncgen(k) for k in xrange(last)]<EOL>_splinefunc_cache[order] = (funclist, condfuncs)<EOL>return funclist, condfuncs<EOL>

Returns the function defined over the left-side pieces for a bspline of
    a given order.

    The 0th piece is the first one less than 0.  The last piece is a function
    identical to 0 (returned as the constant 0).  (There are order//2 + 2 total
    pieces).

    Also returns the condition functions that when evaluated return boolean
    arrays for use with `numpy.piecewise`.


ax = -abs(asarray(x))<EOL>funclist, condfuncs = _bspline_piecefunctions(n)<EOL>condlist = [func(ax) for func in condfuncs]<EOL>return piecewise(ax, condlist, funclist)<EOL>

B-spline basis function of order n.

    Notes
    -----
    Uses numpy.piecewise and automatic function-generator.


signsq = (n + <NUM_LIT:1>) / <NUM_LIT><EOL>return <NUM_LIT:1> / sqrt(<NUM_LIT:2> * pi * signsq) * exp(-x ** <NUM_LIT:2> / <NUM_LIT:2> / signsq)<EOL>

Gaussian approximation to B-spline basis function of order n.


ax = abs(asarray(x))<EOL>res = zeros_like(ax)<EOL>cond1 = less(ax, <NUM_LIT:1>)<EOL>if cond1.any():<EOL><INDENT>ax1 = ax[cond1]<EOL>res[cond1] = <NUM_LIT> / <NUM_LIT:3> - <NUM_LIT:1.0> / <NUM_LIT:2> * ax1 ** <NUM_LIT:2> * (<NUM_LIT:2> - ax1)<EOL><DEDENT>cond2 = ~cond1 & less(ax, <NUM_LIT:2>)<EOL>if cond2.any():<EOL><INDENT>ax2 = ax[cond2]<EOL>res[cond2] = <NUM_LIT:1.0> / <NUM_LIT:6> * (<NUM_LIT:2> - ax2) ** <NUM_LIT:3><EOL><DEDENT>return res<EOL>

A cubic B-spline.

    This is a special case of `bspline`, and equivalent to ``bspline(x, 3)``.


ax = abs(asarray(x))<EOL>res = zeros_like(ax)<EOL>cond1 = less(ax, <NUM_LIT:0.5>)<EOL>if cond1.any():<EOL><INDENT>ax1 = ax[cond1]<EOL>res[cond1] = <NUM_LIT> - ax1 ** <NUM_LIT:2><EOL><DEDENT>cond2 = ~cond1 & less(ax, <NUM_LIT>)<EOL>if cond2.any():<EOL><INDENT>ax2 = ax[cond2]<EOL>res[cond2] = (ax2 - <NUM_LIT>) ** <NUM_LIT:2> / <NUM_LIT><EOL><DEDENT>return res<EOL>

A quadratic B-spline.

    This is a special case of `bspline`, and equivalent to ``bspline(x, 2)``.


if lamb != <NUM_LIT:0.0>:<EOL><INDENT>return _cubic_smooth_coeff(signal, lamb)<EOL><DEDENT>else:<EOL><INDENT>return _cubic_coeff(signal)<EOL><DEDENT>

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.


if lamb != <NUM_LIT:0.0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>return _quadratic_coeff(signal)<EOL><DEDENT>

Compute quadratic spline coefficients for rank-1 array.

    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 .

    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
        Cubic spline coefficients.


def cspline1d_eval(cj, newx, dx=<NUM_LIT:1.0>, x0=<NUM_LIT:0>):

newx = (asarray(newx) - x0) / float(dx)<EOL>res = zeros_like(newx)<EOL>if res.size == <NUM_LIT:0>:<EOL><INDENT>return res<EOL><DEDENT>N = len(cj)<EOL>cond1 = newx < <NUM_LIT:0><EOL>cond2 = newx > (N - <NUM_LIT:1>)<EOL>cond3 = ~(cond1 | cond2)<EOL>res[cond1] = cspline1d_eval(cj, -newx[cond1])<EOL>res[cond2] = cspline1d_eval(cj, <NUM_LIT:2> * (N - <NUM_LIT:1>) - newx[cond2])<EOL>newx = newx[cond3]<EOL>if newx.size == <NUM_LIT:0>:<EOL><INDENT>return res<EOL><DEDENT>result = zeros_like(newx)<EOL>jlower = floor(newx - <NUM_LIT:2>).astype(int) + <NUM_LIT:1><EOL>for i in range(<NUM_LIT:4>):<EOL><INDENT>thisj = jlower + i<EOL>indj = thisj.clip(<NUM_LIT:0>, N - <NUM_LIT:1>)  <EOL>result += cj[indj] * cubic(newx - thisj)<EOL><DEDENT>res[cond3] = result<EOL>return res<EOL>

Evaluate a 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.


def qspline1d_eval(cj, newx, dx=<NUM_LIT:1.0>, x0=<NUM_LIT:0>):

newx = (asarray(newx) - x0) / dx<EOL>res = zeros_like(newx)<EOL>if res.size == <NUM_LIT:0>:<EOL><INDENT>return res<EOL><DEDENT>N = len(cj)<EOL>cond1 = newx < <NUM_LIT:0><EOL>cond2 = newx > (N - <NUM_LIT:1>)<EOL>cond3 = ~(cond1 | cond2)<EOL>res[cond1] = qspline1d_eval(cj, -newx[cond1])<EOL>res[cond2] = qspline1d_eval(cj, <NUM_LIT:2> * (N - <NUM_LIT:1>) - newx[cond2])<EOL>newx = newx[cond3]<EOL>if newx.size == <NUM_LIT:0>:<EOL><INDENT>return res<EOL><DEDENT>result = zeros_like(newx)<EOL>jlower = floor(newx - <NUM_LIT>).astype(int) + <NUM_LIT:1><EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>thisj = jlower + i<EOL>indj = thisj.clip(<NUM_LIT:0>, N - <NUM_LIT:1>)  <EOL>result += cj[indj] * quadratic(newx - thisj)<EOL><DEDENT>res[cond3] = result<EOL>return res<EOL>

Evaluate a quadratic 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.


def axis_slice(a, start=None, stop=None, step=None, axis=-<NUM_LIT:1>):

a_slice = [slice(None)] * a.ndim<EOL>a_slice[axis] = slice(start, stop, step)<EOL>b = a[a_slice]<EOL>return b<EOL>

Take a slice along axis 'axis' from 'a'.

    Parameters
    ----------
    a : numpy.ndarray
        The array to be sliced.
    start, stop, step : int or None
        The slice parameters.
    axis : int
        The axis of `a` to be sliced.

    Examples
    --------
    >>> a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    >>> axis_slice(a, start=0, stop=1, axis=1)
    array([[1],
           [4],
           [7]])
    >>> axis_slice(a, start=1, axis=0)
    array([[4, 5, 6],
           [7, 8, 9]])

    Notes
    -----
    The keyword arguments start, stop and step are used by calling
    slice(start, stop, step).  This implies axis_slice() does not
    handle its arguments the exacty the same as indexing.  To select
    a single index k, for example, use
        axis_slice(a, start=k, stop=k+1)
    In this case, the length of the axis 'axis' in the result will
    be 1; the trivial dimension is not removed. (Use numpy.squeeze()
    to remove trivial axes.)


return axis_slice(a, step=-<NUM_LIT:1>, axis=axis)<EOL>

Reverse the 1-d slices of `a` along axis `axis`.

    Returns axis_slice(a, step=-1, axis=axis).


if n < <NUM_LIT:1>:<EOL><INDENT>return x<EOL><DEDENT>if n > x.shape[axis] - <NUM_LIT:1>:<EOL><INDENT>raise ValueError(("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL>% (n, x.shape[axis] - <NUM_LIT:1>))<EOL><DEDENT>left_end = axis_slice(x, start=<NUM_LIT:0>, stop=<NUM_LIT:1>, axis=axis)<EOL>left_ext = axis_slice(x, start=n, stop=<NUM_LIT:0>, step=-<NUM_LIT:1>, axis=axis)<EOL>right_end = axis_slice(x, start=-<NUM_LIT:1>, axis=axis)<EOL>right_ext = axis_slice(x, start=-<NUM_LIT:2>, stop=-(n + <NUM_LIT:2>), step=-<NUM_LIT:1>, axis=axis)<EOL>ext = np.concatenate((<NUM_LIT:2> * left_end - left_ext,<EOL>x,<EOL><NUM_LIT:2> * right_end - right_ext),<EOL>axis=axis)<EOL>return ext<EOL>

Generate a new ndarray by making an odd extension of x along an axis.

    Parameters
    ----------
    x : ndarray
        The array to be extended.
    n : int
        The number of elements by which to extend x at each end of the axis.
    axis : int
        The axis along which to extend x.  Default is -1.

    Examples
    --------
    >>> a = array([[1.0,2.0,3.0,4.0,5.0], [0.0, 1.0, 4.0, 9.0, 16.0]])
    >>> _odd_ext(a, 2)
    array([[-1.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.],
           [-4., -1,   0.,  1.,  4.,  9., 16., 23., 28.]])


if n < <NUM_LIT:1>:<EOL><INDENT>return x<EOL><DEDENT>if n > x.shape[axis] - <NUM_LIT:1>:<EOL><INDENT>raise ValueError(("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL>% (n, x.shape[axis] - <NUM_LIT:1>))<EOL><DEDENT>left_ext = axis_slice(x, start=n, stop=<NUM_LIT:0>, step=-<NUM_LIT:1>, axis=axis)<EOL>right_ext = axis_slice(x, start=-<NUM_LIT:2>, stop=-(n + <NUM_LIT:2>), step=-<NUM_LIT:1>, axis=axis)<EOL>ext = np.concatenate((left_ext,<EOL>x,<EOL>right_ext),<EOL>axis=axis)<EOL>return ext<EOL>

Create an ndarray that is an even extension of x along an axis.

    Parameters
    ----------
    x : ndarray
        The array to be extended.
    n : int
        The number of elements by which to extend x at each end of the axis.
    axis : int
        The axis along which to extend x.  Default is -1.

    Examples
    --------
    >>> a = array([[1.0,2.0,3.0,4.0,5.0], [0.0, 1.0, 4.0, 9.0, 16.0]])
    >>> _even_ext(a, 2)
    array([[  3.,   2.,   1.,   2.,   3.,   4.,   5.,   4.,   3.],
           [  4.,   1.,   0.,   1.,   4.,   9.,  16.,   9.,   4.]])


if n < <NUM_LIT:1>:<EOL><INDENT>return x<EOL><DEDENT>left_end = axis_slice(x, start=<NUM_LIT:0>, stop=<NUM_LIT:1>, axis=axis)<EOL>ones_shape = [<NUM_LIT:1>] * x.ndim<EOL>ones_shape[axis] = n<EOL>ones = np.ones(ones_shape, dtype=x.dtype)<EOL>left_ext = ones * left_end<EOL>right_end = axis_slice(x, start=-<NUM_LIT:1>, axis=axis)<EOL>right_ext = ones * right_end<EOL>ext = np.concatenate((left_ext,<EOL>x,<EOL>right_ext),<EOL>axis=axis)<EOL>return ext<EOL>

Create an ndarray that is a constant extension of x along an axis.

    The extension repeats the values at the first and last element of
    the axis.

    Parameters
    ----------
    x : ndarray
        The array to be extended.
    n : int
        The number of elements by which to extend x at each end of the axis.
    axis : int
        The axis along which to extend x.  Default is -1.

    Examples
    --------
    >>> a = array([[1.0,2.0,3.0,4.0,5.0], [0.0, 1.0, 4.0, 9.0, 16.0]])
    >>> _const_ext(a, 2)
    array([[  1.,   1.,   1.,   2.,   3.,   4.,   5.,   5.,   5.],
           [  0.,   0.,   0.,   1.,   4.,   9.,  16.,  16.,  16.]])


def pchip_interpolate(xi, yi, x, der=<NUM_LIT:0>, axis=<NUM_LIT:0>):

P = PchipInterpolator(xi, yi, axis=axis)<EOL>if der == <NUM_LIT:0>:<EOL><INDENT>return P(x)<EOL><DEDENT>elif _isscalar(der):<EOL><INDENT>return P(x, der=der)<EOL><DEDENT>else:<EOL><INDENT>return [P(x, nu) for nu in der]<EOL><DEDENT>

Convenience function for pchip interpolation.
xi and yi are arrays of values used to approximate some function f,
with ``yi = f(xi)``.  The interpolant uses monotonic cubic splines
to find the value of new points x and the derivatives there.

See `PchipInterpolator` for details.

Parameters
----------
xi : array_like
    A sorted list of x-coordinates, of length N.
yi :  array_like
    A 1-D array of real values.  `yi`'s length along the interpolation
    axis must be equal to the length of `xi`. If N-D array, use axis
    parameter to select correct axis.
x : scalar or array_like
    Of length M.
der : integer or list
    How many derivatives to extract; None for all potentially
    nonzero derivatives (that is a number equal to the number
    of points), or a list of derivatives to extract. This number
    includes the function value as 0th derivative.
axis : int, optional
    Axis in the yi array corresponding to the x-coordinate values.

See Also
--------
PchipInterpolator

Returns
-------
y : scalar or array_like
    The result, of length R or length M or M by R,


def __call__(self, x, der=<NUM_LIT:0>, extrapolate=None):

out = self._bpoly(x, der, extrapolate)<EOL>return self._reshaper(x, out)<EOL>

Evaluate the PCHIP interpolant or its derivative.

Parameters
----------
x : array-like
    Points to evaluate the interpolant at.
der : int, optional
    Order of derivative to evaluate. Must be non-negative.
extrapolate : bool, optional
    Whether to extrapolate to ouf-of-bounds points based on first
    and last intervals, or to return NaNs.

Returns
-------
y : array-like
    Interpolated values. Shape is determined by replacing
    the interpolation axis in the original array with the shape of x.


t = object.__new__(self.__class__)<EOL>t.axis = self.axis<EOL>t._bpoly = self._bpoly.derivative(der)<EOL>return t<EOL>

Construct a piecewise polynomial representing the derivative.

Parameters
----------
der : int, optional
    Order of derivative to evaluate. (Default: 1)
    If negative, the antiderivative is returned.

Returns
-------
Piecewise polynomial of order k2 = k - der representing the derivative
of this polynomial.


return (PPoly.from_bernstein_basis(self._bpoly)).roots()<EOL>

Return the roots of the interpolated function.


<EOL>xy = array([[a, b] for a in asarray(x) for b in asarray(y)])<EOL>return xy.T<EOL>

Helper function to create an array of pairs of x and y.


import sys<EOL>if hasattr(sys.modules['<STR_LIT:__main__>'], '<STR_LIT>'):<EOL><INDENT>sys.stderr.write("<STR_LIT>".join(map(str, a)) + "<STR_LIT:\n>")<EOL><DEDENT>

Produce some output if file run directly


out = np.zeros((len(xps), c.shape[<NUM_LIT:2>]))<EOL>for i, xp in enumerate(xps):<EOL><INDENT>if xp < <NUM_LIT:0> or xp > <NUM_LIT:1>:<EOL><INDENT>out[i,:] = np.nan<EOL>continue<EOL><DEDENT>j = np.searchsorted(x, xp) - <NUM_LIT:1><EOL>d = xp - x[j]<EOL>assert_(x[j] <= xp < x[j+<NUM_LIT:1>])<EOL>r = sum(c[k,j] * d**(c.shape[<NUM_LIT:0>]-k-<NUM_LIT:1>)<EOL>for k in range(c.shape[<NUM_LIT:0>]))<EOL>out[i,:] = r<EOL><DEDENT>return out<EOL>


def _ppoly_eval_2(coeffs, breaks, xnew, fill=np.nan):

a = breaks[<NUM_LIT:0>]<EOL>b = breaks[-<NUM_LIT:1>]<EOL>K = coeffs.shape[<NUM_LIT:0>]<EOL>saveshape = np.shape(xnew)<EOL>xnew = np.ravel(xnew)<EOL>res = np.empty_like(xnew)<EOL>mask = (xnew >= a) & (xnew <= b)<EOL>res[~mask] = fill<EOL>xx = xnew.compress(mask)<EOL>indxs = np.searchsorted(breaks, xx)-<NUM_LIT:1><EOL>indxs = indxs.clip(<NUM_LIT:0>, len(breaks))<EOL>pp = coeffs<EOL>diff = xx - breaks.take(indxs)<EOL>V = np.vander(diff, N=K)<EOL>values = np.array([np.dot(V[k, :], pp[:, indxs[k]]) for k in xrange(len(xx))])<EOL>res[mask] = values<EOL>res.shape = saveshape<EOL>return res<EOL>

Evaluate piecewise polynomial manually (another way)


olderr = np.seterr(all="<STR_LIT:ignore>")<EOL>try:<EOL><INDENT>x = linspace(<NUM_LIT:0>,<NUM_LIT:10>,<NUM_LIT:9>)<EOL>y = sin(x)<EOL>rbf = Rbf(x, y, function=function)<EOL>yi = rbf(x)<EOL>assert_array_almost_equal(y, yi)<EOL>assert_almost_equal(rbf(float(x[<NUM_LIT:0>])), y[<NUM_LIT:0>])<EOL><DEDENT>finally:<EOL><INDENT>np.seterr(**olderr)<EOL><DEDENT>

Check that the Rbf function interpolates through the nodes (1D)


olderr = np.seterr(all="<STR_LIT:ignore>")<EOL>try:<EOL><INDENT>x = random.rand(<NUM_LIT:50>,<NUM_LIT:1>)*<NUM_LIT:4>-<NUM_LIT:2><EOL>y = random.rand(<NUM_LIT:50>,<NUM_LIT:1>)*<NUM_LIT:4>-<NUM_LIT:2><EOL>z = x*exp(-x**<NUM_LIT:2>-<NUM_LIT>*y**<NUM_LIT:2>)<EOL>rbf = Rbf(x, y, z, epsilon=<NUM_LIT:2>, function=function)<EOL>zi = rbf(x, y)<EOL>zi.shape = x.shape<EOL>assert_array_almost_equal(z, zi)<EOL><DEDENT>finally:<EOL><INDENT>np.seterr(**olderr)<EOL><DEDENT>

Check that the Rbf function interpolates through the nodes (2D)


olderr = np.seterr(all="<STR_LIT:ignore>")<EOL>try:<EOL><INDENT>x = random.rand(<NUM_LIT:50>,<NUM_LIT:1>)*<NUM_LIT:4>-<NUM_LIT:2><EOL>y = random.rand(<NUM_LIT:50>,<NUM_LIT:1>)*<NUM_LIT:4>-<NUM_LIT:2><EOL>z = random.rand(<NUM_LIT:50>,<NUM_LIT:1>)*<NUM_LIT:4>-<NUM_LIT:2><EOL>d = x*exp(-x**<NUM_LIT:2>-y**<NUM_LIT:2>)<EOL>rbf = Rbf(x, y, z, d, epsilon=<NUM_LIT:2>, function=function)<EOL>di = rbf(x, y, z)<EOL>di.shape = x.shape<EOL>assert_array_almost_equal(di, d)<EOL><DEDENT>finally:<EOL><INDENT>np.seterr(**olderr)<EOL><DEDENT>

Check that the Rbf function interpolates through the nodes (3D)


olderr = np.seterr(all="<STR_LIT:ignore>")<EOL>try:<EOL><INDENT>x = linspace(<NUM_LIT:0>, <NUM_LIT:10>, <NUM_LIT:9>)<EOL>y = sin(x)<EOL>rbf = Rbf(x, y, function=function)<EOL>xi = linspace(<NUM_LIT:0>, <NUM_LIT:10>, <NUM_LIT:100>)<EOL>yi = rbf(xi)<EOL>msg = "<STR_LIT>" % abs(yi - sin(xi)).max()<EOL>assert_(allclose(yi, sin(xi), atol=atol), msg)<EOL><DEDENT>finally:<EOL><INDENT>np.seterr(**olderr)<EOL><DEDENT>

Check that the Rbf function approximates a smooth function well away
    from the nodes.


if len(x) == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>return functools.reduce(operator.mul, x)<EOL>

Product of a list of numbers; ~40x faster vs np.prod for Python tuples


M = len(x)<EOL>p = poly1d(<NUM_LIT:0.0>)<EOL>for j in xrange(M):<EOL><INDENT>pt = poly1d(w[j])<EOL>for k in xrange(M):<EOL><INDENT>if k == j:<EOL><INDENT>continue<EOL><DEDENT>fac = x[j]-x[k]<EOL>pt *= poly1d([<NUM_LIT:1.0>, -x[k]])/fac<EOL><DEDENT>p += pt<EOL><DEDENT>return p<EOL>

Return a Lagrange interpolating polynomial.

Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating
polynomial through the points ``(x, w)``.

Warning: This implementation is numerically unstable. Do not expect to
be able to use more than about 20 points even if they are chosen optimally.

Parameters
----------
x : array_like
    `x` represents the x-coordinates of a set of datapoints.
w : array_like
    `w` represents the y-coordinates of a set of datapoints, i.e. f(`x`).

Returns
-------
lagrange : numpy.poly1d instance
    The Lagrange interpolating polynomial.


def interpn(points, values, xi, method="<STR_LIT>", bounds_error=True,<EOL>fill_value=np.nan):

<EOL>if method not in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>method)<EOL><DEDENT>if not hasattr(values, '<STR_LIT>'):<EOL><INDENT>values = np.asarray(values)<EOL><DEDENT>ndim = values.ndim<EOL>if ndim > <NUM_LIT:2> and method == "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if not bounds_error and fill_value is None and method == "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(points) > ndim:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % (len(points), ndim))<EOL><DEDENT>if len(points) != ndim and method == '<STR_LIT>':<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>for i, p in enumerate(points):<EOL><INDENT>if not np.all(np.diff(p) > <NUM_LIT:0.>):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % i)<EOL><DEDENT>if not np.asarray(p).ndim == <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % i)<EOL><DEDENT>if not values.shape[i] == len(p):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % (len(p), values.shape[i], i))<EOL><DEDENT><DEDENT>grid = tuple([np.asarray(p) for p in points])<EOL>xi = _ndim_coords_from_arrays(xi, ndim=len(grid))<EOL>if xi.shape[-<NUM_LIT:1>] != len(grid):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (xi.shape[<NUM_LIT:1>], len(grid)))<EOL><DEDENT>for i, p in enumerate(xi.T):<EOL><INDENT>if bounds_error and not np.logical_and(np.all(grid[i][<NUM_LIT:0>] <= p),<EOL>np.all(p <= grid[i][-<NUM_LIT:1>])):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % i)<EOL><DEDENT><DEDENT>if method == "<STR_LIT>":<EOL><INDENT>interp = RegularGridInterpolator(points, values, method="<STR_LIT>",<EOL>bounds_error=bounds_error,<EOL>fill_value=fill_value)<EOL>return interp(xi)<EOL><DEDENT>elif method == "<STR_LIT>":<EOL><INDENT>interp = RegularGridInterpolator(points, values, method="<STR_LIT>",<EOL>bounds_error=bounds_error,<EOL>fill_value=fill_value)<EOL>return interp(xi)<EOL><DEDENT>elif method == "<STR_LIT>":<EOL><INDENT>xi_shape = xi.shape<EOL>xi = xi.reshape(-<NUM_LIT:1>, xi.shape[-<NUM_LIT:1>])<EOL>idx_valid = np.all((grid[<NUM_LIT:0>][<NUM_LIT:0>] <= xi[:, <NUM_LIT:0>], xi[:, <NUM_LIT:0>] <= grid[<NUM_LIT:0>][-<NUM_LIT:1>],<EOL>grid[<NUM_LIT:1>][<NUM_LIT:0>] <= xi[:, <NUM_LIT:1>], xi[:, <NUM_LIT:1>] <= grid[<NUM_LIT:1>][-<NUM_LIT:1>]),<EOL>axis=<NUM_LIT:0>)<EOL>result = np.empty_like(xi[:, <NUM_LIT:0>])<EOL>interp = RectBivariateSpline(points[<NUM_LIT:0>], points[<NUM_LIT:1>], values[:])<EOL>result[idx_valid] = interp.ev(xi[idx_valid, <NUM_LIT:0>], xi[idx_valid, <NUM_LIT:1>])<EOL>result[np.logical_not(idx_valid)] = fill_value<EOL>return result.reshape(xi_shape[:-<NUM_LIT:1>])<EOL><DEDENT>

Multidimensional interpolation on regular grids.

Parameters
----------
points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
    The points defining the regular grid in n dimensions.

values : array_like, shape (m1, ..., mn, ...)
    The data on the regular grid in n dimensions.

xi : ndarray of shape (..., ndim)
    The coordinates to sample the gridded data at

method : str
    The method of interpolation to perform. Supported are "linear" and
    "nearest", and "splinef2d". "splinef2d" is only supported for
    2-dimensional data.

bounds_error : bool, optional
    If True, when interpolated values are requested outside of the
    domain of the input data, a ValueError is raised.
    If False, then `fill_value` is used.

fill_value : number, optional
    If provided, the value to use for points outside of the
    interpolation domain. If None, values outside
    the domain are extrapolated.  Extrapolation is not supported by method
    "splinef2d".

Returns
-------
values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
    Interpolated values at input coordinates.

Notes
-----

.. versionadded:: 0.14

See also
--------
NearestNDInterpolator : Nearest neighbour interpolation on unstructured
                        data in N dimensions

LinearNDInterpolator : Piecewise linear interpolant on unstructured data
                       in N dimensions

RegularGridInterpolator : Linear and nearest-neighbor Interpolation on a
                          regular grid in arbitrary dimensions

RectBivariateSpline : Bivariate spline approximation over a rectangular mesh


if b.ndim <= <NUM_LIT:2>:<EOL><INDENT>return dot(a, b)<EOL><DEDENT>else:<EOL><INDENT>axes = list(range(b.ndim))<EOL>axes.insert(-<NUM_LIT:1>, <NUM_LIT:0>)<EOL>axes.pop(<NUM_LIT:0>)<EOL>return dot(a, b.transpose(axes))<EOL><DEDENT>

Similar to numpy.dot, but sum over last axis of a and 1st axis of b


def splmake(xk, yk, order=<NUM_LIT:3>, kind='<STR_LIT>', conds=None):

yk = np.asanyarray(yk)<EOL>order = int(order)<EOL>if order < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if order == <NUM_LIT:0>:<EOL><INDENT>return xk, yk[:-<NUM_LIT:1>], order<EOL><DEDENT>elif order == <NUM_LIT:1>:<EOL><INDENT>return xk, yk, order<EOL><DEDENT>try:<EOL><INDENT>func = eval('<STR_LIT>' % kind)<EOL><DEDENT>except:<EOL><INDENT>raise NotImplementedError<EOL><DEDENT>B = _fitpack._bsplmat(order, xk)<EOL>coefs = func(xk, yk, order, conds, B)<EOL>return xk, coefs, order<EOL>

Return a representation of a spline given data-points at internal knots

Parameters
----------
xk : array_like
    The input array of x values of rank 1
yk : array_like
    The input array of y values of rank N. `yk` can be an N-d array to
    represent more than one curve, through the same `xk` points. The first
    dimension is assumed to be the interpolating dimension and is the same
    length of `xk`.
order : int, optional
    Order of the spline
kind : str, optional
    Can be 'smoothest', 'not_a_knot', 'fixed', 'clamped', 'natural',
    'periodic', 'symmetric', 'user', 'mixed' and it is ignored if order < 2
conds : optional
    Conds

Returns
-------
splmake : tuple
    Return a (`xk`, `cvals`, `k`) representation of a spline given
    data-points where the (internal) knots are at the data-points.


def spleval(xck, xnew, deriv=<NUM_LIT:0>):

(xj,cvals,k) = xck<EOL>oldshape = np.shape(xnew)<EOL>xx = np.ravel(xnew)<EOL>sh = cvals.shape[<NUM_LIT:1>:]<EOL>res = np.empty(xx.shape + sh, dtype=cvals.dtype)<EOL>for index in np.ndindex(*sh):<EOL><INDENT>sl = (slice(None),)+index<EOL>if issubclass(cvals.dtype.type, np.complexfloating):<EOL><INDENT>res[sl].real = _fitpack._bspleval(xx,xj,cvals.real[sl],k,deriv)<EOL>res[sl].imag = _fitpack._bspleval(xx,xj,cvals.imag[sl],k,deriv)<EOL><DEDENT>else:<EOL><INDENT>res[sl] = _fitpack._bspleval(xx,xj,cvals[sl],k,deriv)<EOL><DEDENT><DEDENT>res.shape = oldshape + sh<EOL>return res<EOL>

Evaluate a fixed spline represented by the given tuple at the new x-values

The `xj` values are the interior knot points.  The approximation
region is `xj[0]` to `xj[-1]`.  If N+1 is the length of `xj`, then `cvals`
should have length N+k where `k` is the order of the spline.

Parameters
----------
(xj, cvals, k) : tuple
    Parameters that define the fixed spline
xj : array_like
    Interior knot points
cvals : array_like
    Curvature
k : int
    Order of the spline
xnew : array_like
    Locations to calculate spline
deriv : int
    Deriv

Returns
-------
spleval : ndarray
    If `cvals` represents more than one curve (`cvals.ndim` > 1) and/or
    `xnew` is N-d, then the result is `xnew.shape` + `cvals.shape[1:]`
    providing the interpolation of multiple curves.

Notes
-----
Internally, an additional `k`-1 knot points are added on either side of
the spline.


return ppform.fromspline(xk, cvals, k)<EOL>

Return a piece-wise polynomial object from a fixed-spline tuple.


def spline(xk, yk, xnew, order=<NUM_LIT:3>, kind='<STR_LIT>', conds=None):

return spleval(splmake(xk,yk,order=order,kind=kind,conds=conds),xnew)<EOL>

Interpolate a curve at new points using a spline fit

Parameters
----------
xk, yk : array_like
    The x and y values that define the curve.
xnew : array_like
    The x values where spline should estimate the y values.
order : int
    Default is 3.
kind : string
    One of {'smoothest'}
conds : Don't know
    Don't know

Returns
-------
spline : ndarray
    An array of y values; the spline evaluated at the positions `xnew`.


def __call__(self, x, y, dx=<NUM_LIT:0>, dy=<NUM_LIT:0>, assume_sorted=False):

x = atleast_1d(x)<EOL>y = atleast_1d(y)<EOL>if x.ndim != <NUM_LIT:1> or y.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not assume_sorted:<EOL><INDENT>x = np.sort(x)<EOL>y = np.sort(y)<EOL><DEDENT>if self.bounds_error or self.fill_value is not None:<EOL><INDENT>out_of_bounds_x = (x < self.x_min) | (x > self.x_max)<EOL>out_of_bounds_y = (y < self.y_min) | (y > self.y_max)<EOL>any_out_of_bounds_x = np.any(out_of_bounds_x)<EOL>any_out_of_bounds_y = np.any(out_of_bounds_y)<EOL><DEDENT>if self.bounds_error and (any_out_of_bounds_x or any_out_of_bounds_y):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>% ((self.x_min, self.x_max),<EOL>(self.y_min, self.y_max)))<EOL><DEDENT>z = fitpack.bisplev(x, y, self.tck, dx, dy)<EOL>z = atleast_2d(z)<EOL>z = transpose(z)<EOL>if self.fill_value is not None:<EOL><INDENT>if any_out_of_bounds_x:<EOL><INDENT>z[:, out_of_bounds_x] = self.fill_value<EOL><DEDENT>if any_out_of_bounds_y:<EOL><INDENT>z[out_of_bounds_y, :] = self.fill_value<EOL><DEDENT><DEDENT>if len(z) == <NUM_LIT:1>:<EOL><INDENT>z = z[<NUM_LIT:0>]<EOL><DEDENT>return array(z)<EOL>

Interpolate the function.

        Parameters
        ----------
        x : 1D array
            x-coordinates of the mesh on which to interpolate.
        y : 1D array
            y-coordinates of the mesh on which to interpolate.
        dx : int >= 0, < kx
            Order of partial derivatives in x.
        dy : int >= 0, < ky
            Order of partial derivatives in y.
        assume_sorted : bool, optional
            If False, values of `x` and `y` can be in any order and they are
            sorted first.
            If True, `x` and `y` have to be arrays of monotonically
            increasing values.

        Returns
        -------
        z : 2D array with shape (len(y), len(x))
            The interpolated values.


def __init__(self, x, y, kind='<STR_LIT>', axis=-<NUM_LIT:1>,<EOL>copy=True, bounds_error=True, fill_value=np.nan,<EOL>assume_sorted=False):

_Interpolator1D.__init__(self, x, y, axis=axis)<EOL>self.copy = copy<EOL>self.bounds_error = bounds_error<EOL>self.fill_value = fill_value<EOL>if kind in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>order = {'<STR_LIT>': <NUM_LIT:0>, '<STR_LIT>': <NUM_LIT:0>,'<STR_LIT>': <NUM_LIT:1>,<EOL>'<STR_LIT>': <NUM_LIT:2>, '<STR_LIT>': <NUM_LIT:3>}[kind]<EOL>kind = '<STR_LIT>'<EOL><DEDENT>elif isinstance(kind, int):<EOL><INDENT>order = kind<EOL>kind = '<STR_LIT>'<EOL><DEDENT>elif kind not in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise NotImplementedError("<STR_LIT>"<EOL>"<STR_LIT>" % kind)<EOL><DEDENT>x = array(x, copy=self.copy)<EOL>y = array(y, copy=self.copy)<EOL>if not assume_sorted:<EOL><INDENT>ind = np.argsort(x)<EOL>x = x[ind]<EOL>y = np.take(y, ind, axis=axis)<EOL><DEDENT>if x.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if y.ndim == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not issubclass(y.dtype.type, np.inexact):<EOL><INDENT>y = y.astype(np.float_)<EOL><DEDENT>self.axis = axis % y.ndim<EOL>self.y = y<EOL>y = self._reshape_yi(y)<EOL>if kind in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>minval = <NUM_LIT:2><EOL>if kind == '<STR_LIT>':<EOL><INDENT>self.x_bds = (x[<NUM_LIT:1>:] + x[:-<NUM_LIT:1>]) / <NUM_LIT><EOL>self._call = self.__class__._call_nearest<EOL><DEDENT>else:<EOL><INDENT>self._call = self.__class__._call_linear<EOL><DEDENT><DEDENT>else:<EOL><INDENT>minval = order + <NUM_LIT:1><EOL>self._spline = splmake(x, y, order=order)<EOL>self._call = self.__class__._call_spline<EOL><DEDENT>if len(x) < minval:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % minval)<EOL><DEDENT>self._kind = kind<EOL>self.x = x<EOL>self._y = y<EOL>

Initialize a 1D linear interpolation class.


<EOL>x_new_indices = searchsorted(self.x_bds, x_new, side='<STR_LIT:left>')<EOL>x_new_indices = x_new_indices.clip(<NUM_LIT:0>, len(self.x)-<NUM_LIT:1>).astype(intp)<EOL>y_new = self._y[x_new_indices]<EOL>return y_new<EOL>

Find nearest neighbour interpolated y_new = f(x_new).


<EOL>below_bounds = x_new < self.x[<NUM_LIT:0>]<EOL>above_bounds = x_new > self.x[-<NUM_LIT:1>]<EOL>if self.bounds_error and below_bounds.any():<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if self.bounds_error and above_bounds.any():<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>out_of_bounds = logical_or(below_bounds, above_bounds)<EOL>return out_of_bounds<EOL>

Check the inputs for being in the bounds of the interpolated data.

        Parameters
        ----------
        x_new : array

        Returns
        -------
        out_of_bounds : bool array
            The mask on x_new of values that are out of the bounds.


@classmethod<EOL><INDENT>def construct_fast(cls, c, x, extrapolate=None):<DEDENT>

self = object.__new__(cls)<EOL>self.c = c<EOL>self.x = x<EOL>if extrapolate is None:<EOL><INDENT>extrapolate = True<EOL><DEDENT>self.extrapolate = extrapolate<EOL>return self<EOL>

Construct the piecewise polynomial without making checks.

Takes the same parameters as the constructor. Input arguments
`c` and `x` must be arrays of the correct shape and type.  The
`c` array can only be of dtypes float and complex, and `x`
array must have dtype float.


if not self.x.flags.c_contiguous:<EOL><INDENT>self.x = self.x.copy()<EOL><DEDENT>if not self.c.flags.c_contiguous:<EOL><INDENT>self.c = self.c.copy()<EOL><DEDENT>

c and x may be modified by the user. The Cython code expects
that they are C contiguous.


c = np.asarray(c)<EOL>x = np.asarray(x)<EOL>if c.ndim < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if x.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if x.shape[<NUM_LIT:0>] != c.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if c.shape[<NUM_LIT:2>:] != self.c.shape[<NUM_LIT:2>:] or c.ndim != self.c.ndim:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if right:<EOL><INDENT>if x[<NUM_LIT:0>] < self.x[-<NUM_LIT:1>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if x[-<NUM_LIT:1>] > self.x[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>if c.size == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>dtype = self._get_dtype(c.dtype)<EOL>k2 = max(c.shape[<NUM_LIT:0>], self.c.shape[<NUM_LIT:0>])<EOL>c2 = np.zeros((k2, self.c.shape[<NUM_LIT:1>] + c.shape[<NUM_LIT:1>]) + self.c.shape[<NUM_LIT:2>:],<EOL>dtype=dtype)<EOL>if right:<EOL><INDENT>c2[k2-self.c.shape[<NUM_LIT:0>]:, :self.c.shape[<NUM_LIT:1>]] = self.c<EOL>c2[k2-c.shape[<NUM_LIT:0>]:, self.c.shape[<NUM_LIT:1>]:] = c<EOL>self.x = np.r_[self.x, x]<EOL><DEDENT>else:<EOL><INDENT>c2[k2-self.c.shape[<NUM_LIT:0>]:, :c.shape[<NUM_LIT:1>]] = c<EOL>c2[k2-c.shape[<NUM_LIT:0>]:, c.shape[<NUM_LIT:1>]:] = self.c<EOL>self.x = np.r_[x, self.x]<EOL><DEDENT>self.c = c2<EOL>

Add additional breakpoints and coefficients to the polynomial.

Parameters
----------
c : ndarray, size (k, m, ...)
    Additional coefficients for polynomials in intervals
    ``self.x[-1] <= x < x_right[0]``, ``x_right[0] <= x < x_right[1]``,
    ..., ``x_right[m-2] <= x < x_right[m-1]``
x : ndarray, size (m,)
    Additional breakpoints. Must be sorted and either to
    the right or to the left of the current breakpoints.
right : bool, optional
    Whether the new intervals are to the right or to the left
    of the current intervals.


def __call__(self, x, nu=<NUM_LIT:0>, extrapolate=None):

if extrapolate is None:<EOL><INDENT>extrapolate = self.extrapolate<EOL><DEDENT>x = np.asarray(x)<EOL>x_shape = x.shape<EOL>x = np.ascontiguousarray(x.ravel(), dtype=np.float_)<EOL>out = np.empty((len(x), prod(self.c.shape[<NUM_LIT:2>:])), dtype=self.c.dtype)<EOL>self._ensure_c_contiguous()<EOL>self._evaluate(x, nu, extrapolate, out)<EOL>return out.reshape(x_shape + self.c.shape[<NUM_LIT:2>:])<EOL>

Evaluate the piecewise polynomial or its derivative

Parameters
----------
x : array-like
    Points to evaluate the interpolant at.
nu : int, optional
    Order of derivative to evaluate. Must be non-negative.
extrapolate : bool, optional
    Whether to extrapolate to ouf-of-bounds points based on first
    and last intervals, or to return NaNs.

Returns
-------
y : array-like
    Interpolated values. Shape is determined by replacing
    the interpolation axis in the original array with the shape of x.

Notes
-----
Derivatives are evaluated piecewise for each polynomial
segment, even if the polynomial is not differentiable at the
breakpoints. The polynomial intervals are considered half-open,
``[a, b)``, except for the last interval which is closed
``[a, b]``.


if nu < <NUM_LIT:0>:<EOL><INDENT>return self.antiderivative(-nu)<EOL><DEDENT>if nu == <NUM_LIT:0>:<EOL><INDENT>c2 = self.c.copy()<EOL><DEDENT>else:<EOL><INDENT>c2 = self.c[:-nu,:].copy()<EOL><DEDENT>if c2.shape[<NUM_LIT:0>] == <NUM_LIT:0>:<EOL><INDENT>c2 = np.zeros((<NUM_LIT:1>,) + c2.shape[<NUM_LIT:1>:], dtype=c2.dtype)<EOL><DEDENT>factor = spec.poch(np.arange(c2.shape[<NUM_LIT:0>], <NUM_LIT:0>, -<NUM_LIT:1>), nu)<EOL>c2 *= factor[(slice(None),) + (None,)*(c2.ndim-<NUM_LIT:1>)]<EOL>return self.construct_fast(c2, self.x, self.extrapolate)<EOL>

Construct a new piecewise polynomial representing the derivative.

Parameters
----------
n : int, optional
    Order of derivative to evaluate. (Default: 1)
    If negative, the antiderivative is returned.

Returns
-------
pp : PPoly
    Piecewise polynomial of order k2 = k - n representing the derivative
    of this polynomial.

Notes
-----
Derivatives are evaluated piecewise for each polynomial
segment, even if the polynomial is not differentiable at the
breakpoints. The polynomial intervals are considered half-open,
``[a, b)``, except for the last interval which is closed
``[a, b]``.


if nu <= <NUM_LIT:0>:<EOL><INDENT>return self.derivative(-nu)<EOL><DEDENT>c = np.zeros((self.c.shape[<NUM_LIT:0>] + nu, self.c.shape[<NUM_LIT:1>]) + self.c.shape[<NUM_LIT:2>:],<EOL>dtype=self.c.dtype)<EOL>c[:-nu] = self.c<EOL>factor = spec.poch(np.arange(self.c.shape[<NUM_LIT:0>], <NUM_LIT:0>, -<NUM_LIT:1>), nu)<EOL>c[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-<NUM_LIT:1>)]<EOL>self._ensure_c_contiguous()<EOL>_ppoly.fix_continuity(c.reshape(c.shape[<NUM_LIT:0>], c.shape[<NUM_LIT:1>], -<NUM_LIT:1>),<EOL>self.x, nu)<EOL>return self.construct_fast(c, self.x, self.extrapolate)<EOL>

Construct a new piecewise polynomial representing the antiderivative.

Antiderivativative is also the indefinite integral of the function,
and derivative is its inverse operation.

Parameters
----------
n : int, optional
    Order of antiderivative to evaluate. (Default: 1)
    If negative, the derivative is returned.

Returns
-------
pp : PPoly
    Piecewise polynomial of order k2 = k + n representing
    the antiderivative of this polynomial.

Notes
-----
The antiderivative returned by this function is continuous and
continuously differentiable to order n-1, up to floating point
rounding error.


def integrate(self, a, b, extrapolate=None):

if extrapolate is None:<EOL><INDENT>extrapolate = self.extrapolate<EOL><DEDENT>sign = <NUM_LIT:1><EOL>if b < a:<EOL><INDENT>a, b = b, a<EOL>sign = -<NUM_LIT:1><EOL><DEDENT>range_int = np.empty((prod(self.c.shape[<NUM_LIT:2>:]),), dtype=self.c.dtype)<EOL>self._ensure_c_contiguous()<EOL>_ppoly.integrate(self.c.reshape(self.c.shape[<NUM_LIT:0>], self.c.shape[<NUM_LIT:1>], -<NUM_LIT:1>),<EOL>self.x, a, b, bool(extrapolate),<EOL>out=range_int)<EOL>range_int *= sign<EOL>return range_int.reshape(self.c.shape[<NUM_LIT:2>:])<EOL>

Compute a definite integral over a piecewise polynomial.

Parameters
----------
a : float
    Lower integration bound
b : float
    Upper integration bound
extrapolate : bool, optional
    Whether to extrapolate to ouf-of-bounds points based on first
    and last intervals, or to return NaNs.

Returns
-------
ig : array_like
    Definite integral of the piecewise polynomial over [a, b]


def roots(self, discontinuity=True, extrapolate=None):

if extrapolate is None:<EOL><INDENT>extrapolate = self.extrapolate<EOL><DEDENT>self._ensure_c_contiguous()<EOL>if np.issubdtype(self.c.dtype, np.complexfloating):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>r = _ppoly.real_roots(self.c.reshape(self.c.shape[<NUM_LIT:0>], self.c.shape[<NUM_LIT:1>], -<NUM_LIT:1>),<EOL>self.x, bool(discontinuity),<EOL>bool(extrapolate))<EOL>if self.c.ndim == <NUM_LIT:2>:<EOL><INDENT>return r[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>r2 = np.empty(prod(self.c.shape[<NUM_LIT:2>:]), dtype=object)<EOL>for ii, root in enumerate(r):<EOL><INDENT>r2[ii] = root<EOL><DEDENT>return r2.reshape(self.c.shape[<NUM_LIT:2>:])<EOL><DEDENT>

Find real roots of the piecewise polynomial.

Parameters
----------
discontinuity : bool, optional
    Whether to report sign changes across discontinuities at
    breakpoints as roots.
extrapolate : bool, optional
    Whether to return roots from the polynomial extrapolated
    based on first and last intervals.

Returns
-------
roots : ndarray
    Roots of the polynomial(s).

    If the PPoly object describes multiple polynomials, the
    return value is an object array whose each element is an
    ndarray containing the roots.

Notes
-----
This routine works only on real-valued polynomials.

If the piecewise polynomial contains sections that are
identically zero, the root list will contain the start point
of the corresponding interval, followed by a ``nan`` value.

If the polynomial is discontinuous across a breakpoint, and
there is a sign change across the breakpoint, this is reported
if the `discont` parameter is True.

Examples
--------

Finding roots of ``[x**2 - 1, (x - 1)**2]`` defined on intervals
``[-2, 1], [1, 2]``:

>>> from scipy.interpolate import PPoly
>>> pp = PPoly(np.array([[1, 0, -1], [1, 0, 0]]).T, [-2, 1, 2])
>>> pp.roots()
array([-1.,  1.])


@classmethod<EOL><INDENT>def from_spline(cls, tck, extrapolate=None):<DEDENT>

t, c, k = tck<EOL>cvals = np.empty((k + <NUM_LIT:1>, len(t)-<NUM_LIT:1>), dtype=c.dtype)<EOL>for m in xrange(k, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>y = fitpack.splev(t[:-<NUM_LIT:1>], tck, der=m)<EOL>cvals[k - m, :] = y/spec.gamma(m+<NUM_LIT:1>)<EOL><DEDENT>return cls.construct_fast(cvals, t, extrapolate)<EOL>

Construct a piecewise polynomial from a spline

Parameters
----------
tck
    A spline, as returned by `splrep`
extrapolate : bool, optional
    Whether to extrapolate to ouf-of-bounds points based on first
    and last intervals, or to return NaNs. Default: True.


@classmethod<EOL><INDENT>def from_bernstein_basis(cls, bp, extrapolate=None):<DEDENT>

dx = np.diff(bp.x)<EOL>k = bp.c.shape[<NUM_LIT:0>] - <NUM_LIT:1>  <EOL>rest = (None,)*(bp.c.ndim-<NUM_LIT:2>)<EOL>c = np.zeros_like(bp.c)<EOL>for a in range(k+<NUM_LIT:1>):<EOL><INDENT>factor = (-<NUM_LIT:1>)**(a) * comb(k, a) * bp.c[a]<EOL>for s in range(a, k+<NUM_LIT:1>):<EOL><INDENT>val = comb(k-a, s-a) * (-<NUM_LIT:1>)**s<EOL>c[k-s] += factor * val / dx[(slice(None),)+rest]**s<EOL><DEDENT><DEDENT>if extrapolate is None:<EOL><INDENT>extrapolate = bp.extrapolate<EOL><DEDENT>return cls.construct_fast(c, bp.x, extrapolate)<EOL>

Construct a piecewise polynomial in the power basis
from a polynomial in Bernstein basis.

Parameters
----------
bp : BPoly
    A Bernstein basis polynomial, as created by BPoly
extrapolate : bool, optional
    Whether to extrapolate to ouf-of-bounds points based on first
    and last intervals, or to return NaNs. Default: True.


if nu < <NUM_LIT:0>:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>if nu > <NUM_LIT:1>:<EOL><INDENT>bp = self<EOL>for k in range(nu):<EOL><INDENT>bp = bp.derivative()<EOL><DEDENT>return bp<EOL><DEDENT>if nu == <NUM_LIT:0>:<EOL><INDENT>c2 = self.c.copy()<EOL><DEDENT>else:<EOL><INDENT>rest = (None,)*(self.c.ndim-<NUM_LIT:2>)<EOL>k = self.c.shape[<NUM_LIT:0>] - <NUM_LIT:1><EOL>dx = np.diff(self.x)[(None, slice(None))+rest]<EOL>c2 = k * np.diff(self.c, axis=<NUM_LIT:0>) / dx<EOL><DEDENT>if c2.shape[<NUM_LIT:0>] == <NUM_LIT:0>:<EOL><INDENT>c2 = np.zeros((<NUM_LIT:1>,) + c2.shape[<NUM_LIT:1>:], dtype=c2.dtype)<EOL><DEDENT>return self.construct_fast(c2, self.x, self.extrapolate)<EOL>

Construct a new piecewise polynomial representing the derivative.

Parameters
----------
nu : int, optional
    Order of derivative to evaluate. (Default: 1)
    If negative, the antiderivative is returned.

Returns
-------
bp : BPoly
    Piecewise polynomial of order k2 = k - nu representing the derivative
    of this polynomial.


@classmethod<EOL><INDENT>def from_power_basis(cls, pp, extrapolate=None):<DEDENT>

dx = np.diff(pp.x)<EOL>k = pp.c.shape[<NUM_LIT:0>] - <NUM_LIT:1>   <EOL>rest = (None,)*(pp.c.ndim-<NUM_LIT:2>)<EOL>c = np.zeros_like(pp.c)<EOL>for a in range(k+<NUM_LIT:1>):<EOL><INDENT>factor = pp.c[a] / comb(k, k-a) * dx[(slice(None),)+rest]**(k-a)<EOL>for j in range(k-a, k+<NUM_LIT:1>):<EOL><INDENT>c[j] += factor * comb(j, k-a)<EOL><DEDENT><DEDENT>if extrapolate is None:<EOL><INDENT>extrapolate = pp.extrapolate<EOL><DEDENT>return cls.construct_fast(c, pp.x, extrapolate)<EOL>

Construct a piecewise polynomial in Bernstein basis
from a power basis polynomial.

Parameters
----------
pp : PPoly
    A piecewise polynomial in the power basis
extrapolate : bool, optional
    Whether to extrapolate to ouf-of-bounds points based on first
    and last intervals, or to return NaNs. Default: True.


@classmethod<EOL><INDENT>def from_derivatives(cls, xi, yi, orders=None, extrapolate=None):<DEDENT>

xi = np.asarray(xi)<EOL>if len(xi) != len(yi):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if np.any(xi[<NUM_LIT:1>:] - xi[:<NUM_LIT:1>] <= <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>m = len(xi) - <NUM_LIT:1><EOL>try:<EOL><INDENT>k = max(len(yi[i]) + len(yi[i+<NUM_LIT:1>]) for i in range(m))<EOL><DEDENT>except TypeError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if orders is None:<EOL><INDENT>orders = [None] * m<EOL><DEDENT>else:<EOL><INDENT>if isinstance(orders, integer_types):<EOL><INDENT>orders = [orders] * m<EOL><DEDENT>k = max(k, max(orders))<EOL>if any(o <= <NUM_LIT:0> for o in orders):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>c = []<EOL>for i in range(m):<EOL><INDENT>y1, y2 = yi[i], yi[i+<NUM_LIT:1>]<EOL>if orders[i] is None:<EOL><INDENT>n1, n2 = len(y1), len(y2)<EOL><DEDENT>else:<EOL><INDENT>n = orders[i]+<NUM_LIT:1><EOL>n1 = min(n//<NUM_LIT:2>, len(y1))<EOL>n2 = min(n - n1, len(y2))<EOL>n1 = min(n - n2, len(y2))<EOL>if n1+n2 != n:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(xi[i], len(y1), xi[i+<NUM_LIT:1>], len(y2), orders[i]))<EOL><DEDENT>if not (n1 <= len(y1) and n2 <= len(y2)):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>b = BPoly._construct_from_derivatives(xi[i], xi[i+<NUM_LIT:1>], y1[:n1], y2[:n2])<EOL>if len(b) < k:<EOL><INDENT>b = BPoly._raise_degree(b, k - len(b))<EOL><DEDENT>c.append(b)<EOL><DEDENT>c = np.asarray(c)<EOL>return cls(c.swapaxes(<NUM_LIT:0>, <NUM_LIT:1>), xi, extrapolate)<EOL>

Construct a piecewise polynomial in the Bernstein basis,
        compatible with the specified values and derivatives at breakpoints.

        Parameters
        ----------
        xi : array_like
            sorted 1D array of x-coordinates
        yi : array_like or list of array-likes
            ``yi[i][j]`` is the ``j``-th derivative known at ``xi[i]``
        orders : None or int or array_like of ints. Default: None.
            Specifies the degree of local polynomials. If not None, some
            derivatives are ignored.
        extrapolate : bool, optional
            Whether to extrapolate to ouf-of-bounds points based on first
            and last intervals, or to return NaNs. Default: True.

        Notes
        -----
        If ``k`` derivatives are specified at a breakpoint ``x``, the
        constructed polynomial is exactly ``k`` times continuously
        differentiable at ``x``, unless the ``order`` is provided explicitly.
        In the latter case, the smoothness of the polynomial at
        the breakpoint is controlled by the ``order``.

        Deduces the number of derivatives to match at each end
        from ``order`` and the number of derivatives available. If
        possible it uses the same number of derivatives from
        each end; if the number is odd it tries to take the
        extra one from y2. In any case if not enough derivatives
        are available at one end or another it draws enough to
        make up the total from the other end.

        If the order is too high and not enough derivatives are available,
        an exception is raised.

        Examples
        --------

        >>> BPoly.from_derivatives([0, 1], [[1, 2], [3, 4]])

        Creates a polynomial `f(x)` of degree 3, defined on `[0, 1]`
        such that `f(0) = 1, df/dx(0) = 2, f(1) = 3, df/dx(1) = 4`

        >>> BPoly.from_derivatives([0, 1, 2], [[0, 1], [0], [2]])

        Creates a piecewise polynomial `f(x)`, such that
        `f(0) = f(1) = 0`, `f(2) = 2`, and `df/dx(0) = 1`.
        Based on the number of derivatives provided, the order of the
        local polynomials is 2 on `[0, 1]` and 1 on `[1, 2]`.
        Notice that no restriction is imposed on the derivatives at
        `x = 1` and `x = 2`.

        Indeed, the explicit form of the polynomial is::

            f(x) = | x * (1 - x),  0 <= x < 1
                   | 2 * (x - 1),  1 <= x <= 2

        So that f'(1-0) = -1 and f'(1+0) = 2


@staticmethod<EOL><INDENT>def _construct_from_derivatives(xa, xb, ya, yb):<DEDENT>

ya, yb = np.asarray(ya), np.asarray(yb)<EOL>if ya.shape[<NUM_LIT:1>:] != yb.shape[<NUM_LIT:1>:]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>dta, dtb = ya.dtype, yb.dtype<EOL>if (np.issubdtype(dta, np.complexfloating)<EOL>or np.issubdtype(dtb, np.complexfloating)):<EOL><INDENT>dt = np.complex_<EOL><DEDENT>else:<EOL><INDENT>dt = np.float_<EOL><DEDENT>na, nb = len(ya), len(yb)<EOL>n = na + nb<EOL>c = np.empty((na+nb,) + ya.shape[<NUM_LIT:1>:], dtype=dt)<EOL>for q in range(<NUM_LIT:0>, na):<EOL><INDENT>c[q] = ya[q] / spec.poch(n - q, q) * (xb - xa)**q<EOL>for j in range(<NUM_LIT:0>, q):<EOL><INDENT>c[q] -= (-<NUM_LIT:1>)**(j+q) * comb(q, j) * c[j]<EOL><DEDENT><DEDENT>for q in range(<NUM_LIT:0>, nb):<EOL><INDENT>c[-q-<NUM_LIT:1>] = yb[q] / spec.poch(n - q, q) * (-<NUM_LIT:1>)**q * (xb - xa)**q<EOL>for j in range(<NUM_LIT:0>, q):<EOL><INDENT>c[-q-<NUM_LIT:1>] -= (-<NUM_LIT:1>)**(j+<NUM_LIT:1>) * comb(q, j+<NUM_LIT:1>) * c[-q+j]<EOL><DEDENT><DEDENT>return c<EOL>

Compute the coefficients of a polynomial in the Bernstein basis
        given the values and derivatives at the edges.

        Return the coefficients of a polynomial in the Bernstein basis
        defined on `[xa, xb]` and having the values and derivatives at the
        endpoints ``xa`` and ``xb`` as specified by ``ya`` and ``yb``.
        The polynomial constructed is of the minimal possible degree, i.e.,
        if the lengths of ``ya`` and ``yb`` are ``na`` and ``nb``, the degree
        of the polynomial is ``na + nb - 1``.

        Parameters
        ----------
        xa : float
            Left-hand end point of the interval
        xb : float
            Right-hand end point of the interval
        ya : array_like
            Derivatives at ``xa``. ``ya[0]`` is the value of the function, and
            ``ya[i]`` for ``i > 0`` is the value of the ``i``-th derivative.
        yb : array_like
            Derivatives at ``xb``.

        Returns
        -------
        array
            coefficient array of a polynomial having specified derivatives

        Notes
        -----
        This uses several facts from life of Bernstein basis functions.
        First of all,

            .. math:: b'_{a, n} = n (b_{a-1, n-1} - b_{a, n-1})

        If B(x) is a linear combination of the form

            .. math:: B(x) = \sum_{a=0}^{n} c_a b_{a, n},

        then :math: B'(x) = n \sum_{a=0}^{n-1} (c_{a+1} - c_{a}) b_{a, n-1}.
        Iterating the latter one, one finds for the q-th derivative

            .. math:: B^{q}(x) = n!/(n-q)! \sum_{a=0}^{n-q} Q_a b_{a, n-q},

        with

          .. math:: Q_a = \sum_{j=0}^{q} (-)^{j+q} comb(q, j) c_{j+a}

        This way, only `a=0` contributes to :math: `B^{q}(x = xa)`, and
        `c_q` are found one by one by iterating `q = 0, ..., na`.

        At `x = xb` it's the same with `a = n - q`.


if d == <NUM_LIT:0>:<EOL><INDENT>return c<EOL><DEDENT>k = c.shape[<NUM_LIT:0>] - <NUM_LIT:1><EOL>out = np.zeros((c.shape[<NUM_LIT:0>] + d,) + c.shape[<NUM_LIT:1>:], dtype=c.dtype)<EOL>for a in range(c.shape[<NUM_LIT:0>]):<EOL><INDENT>f = c[a] * comb(k, a)<EOL>for j in range(d+<NUM_LIT:1>):<EOL><INDENT>out[a+j] += f * comb(d, j) / comb(k+d, a+j)<EOL><DEDENT><DEDENT>return out<EOL>

Raise a degree of a polynomial in the Bernstein basis.

        Given the coefficients of a polynomial degree `k`, return (the
        coefficients of) the equivalent polynomial of degree `k+d`.

        Parameters
        ----------
        c : array_like
            coefficient array, 1D
        d : integer

        Returns
        -------
        array
            coefficient array, 1D array of length `c.shape[0] + d`

        Notes
        -----
        This uses the fact that a Bernstein polynomial `b_{a, k}` can be
        identically represented as a linear combination of polynomials of
        a higher degree `k+d`:

            .. math:: b_{a, k} = comb(k, a) \sum_{j=0}^{d} b_{a+j, k+d} \
                                comb(d, j) / comb(k+d, a+j)


method = self.method if method is None else method<EOL>if method not in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>raise ValueError("<STR_LIT>" % method)<EOL><DEDENT>ndim = len(self.grid)<EOL>xi = _ndim_coords_from_arrays(xi, ndim=ndim)<EOL>if xi.shape[-<NUM_LIT:1>] != len(self.grid):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (xi.shape[<NUM_LIT:1>], ndim))<EOL><DEDENT>xi_shape = xi.shape<EOL>xi = xi.reshape(-<NUM_LIT:1>, xi_shape[-<NUM_LIT:1>])<EOL>if self.bounds_error:<EOL><INDENT>for i, p in enumerate(xi.T):<EOL><INDENT>if not np.logical_and(np.all(self.grid[i][<NUM_LIT:0>] <= p),<EOL>np.all(p <= self.grid[i][-<NUM_LIT:1>])):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % i)<EOL><DEDENT><DEDENT><DEDENT>indices, norm_distances, out_of_bounds = self._find_indices(xi.T)<EOL>if method == "<STR_LIT>":<EOL><INDENT>result = self._evaluate_linear(indices, norm_distances, out_of_bounds)<EOL><DEDENT>elif method == "<STR_LIT>":<EOL><INDENT>result = self._evaluate_nearest(indices, norm_distances, out_of_bounds)<EOL><DEDENT>if not self.bounds_error and self.fill_value is not None:<EOL><INDENT>result[out_of_bounds] = self.fill_value<EOL><DEDENT>return result.reshape(xi_shape[:-<NUM_LIT:1>] + self.values.shape[ndim:])<EOL>

Interpolation at coordinates

Parameters
----------
xi : ndarray of shape (..., ndim)
    The coordinates to sample the gridded data at

method : str
    The method of interpolation to perform. Supported are "linear" and
    "nearest".


@classmethod<EOL><INDENT>def _from_tck(cls, tck, ext=<NUM_LIT:0>):<DEDENT>

self = cls.__new__(cls)<EOL>t, c, k = tck<EOL>self._eval_args = tck<EOL>self._data = (None,None,None,None,None,k,None,len(t),t,<EOL>c,None,None,None,None)<EOL>self.ext = ext<EOL>return self<EOL>

Construct a spline object from given tck


data = self._data<EOL>if data[<NUM_LIT:6>] == -<NUM_LIT:1>:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>return<EOL><DEDENT>args = data[:<NUM_LIT:6>] + (s,) + data[<NUM_LIT:7>:]<EOL>data = dfitpack.fpcurf1(*args)<EOL>if data[-<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>data = self._reset_nest(data)<EOL><DEDENT>self._data = data<EOL>self._reset_class()<EOL>

Continue spline computation with the given smoothing
        factor s and with the knots found at the last call.

        This routine modifies the spline in place.


def __call__(self, x, nu=<NUM_LIT:0>, ext=None):

x = np.asarray(x)<EOL>if x.size == <NUM_LIT:0>:<EOL><INDENT>return array([])<EOL>

Evaluate spline (or its nu-th derivative) at positions x.

Parameters
----------
x : array_like
    A 1-D array of points at which to return the value of the smoothed
    spline or its derivatives. Note: x can be unordered but the
    evaluation is more efficient if x is (partially) ordered.
nu  : int
    The order of derivative of the spline to compute.
ext : int
    Controls the value returned for elements of ``x`` not in the
    interval defined by the knot sequence.

    * if ext=0 or 'extrapolate', return the extrapolated value.
    * if ext=1 or 'zeros', return 0
    * if ext=2 or 'raise', raise a ValueError
    * if ext=3 or 'const', return the boundary value.

    The default value is 0, passed from the initialization of
    UnivariateSpline.


data = self._data<EOL>k,n = data[<NUM_LIT:5>],data[<NUM_LIT:7>]<EOL>return data[<NUM_LIT:8>][k:n-k]<EOL>

Return positions of (boundary and interior) knots of the spline.


data = self._data<EOL>k,n = data[<NUM_LIT:5>],data[<NUM_LIT:7>]<EOL>return data[<NUM_LIT:9>][:n-k-<NUM_LIT:1>]<EOL>


return self._data[<NUM_LIT:10>]<EOL>

Return weighted sum of squared residuals of the spline
        approximation: ``sum((w[i] * (y[i]-spl(x[i])))**2, axis=0)``.


return dfitpack.splint(*(self._eval_args+(a,b)))<EOL>

Return definite integral of the spline between two given points.


d,ier = dfitpack.spalde(*(self._eval_args+(x,)))<EOL>if not ier == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % ier)<EOL><DEDENT>return d<EOL>

Return all derivatives of the spline at the point x.


k = self._data[<NUM_LIT:5>]<EOL>if k == <NUM_LIT:3>:<EOL><INDENT>z,m,ier = dfitpack.sproot(*self._eval_args[:<NUM_LIT:2>])<EOL>if not ier == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % ier)<EOL><DEDENT>return z[:m]<EOL><DEDENT>raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>

Return the zeros of the spline.

        Restriction: only cubic splines are supported by fitpack.


tck = fitpack.splder(self._eval_args, n)<EOL>return UnivariateSpline._from_tck(tck, self.ext)<EOL>

Construct a new spline representing the derivative of this spline.

Parameters
----------
n : int, optional
    Order of derivative to evaluate. Default: 1

Returns
-------
spline : UnivariateSpline
    Spline of order k2=k-n representing the derivative of this
    spline.

See Also
--------
splder, antiderivative

Notes
-----

.. versionadded:: 0.13.0

Examples
--------
This can be used for finding maxima of a curve:

>>> from scipy.interpolate import UnivariateSpline
>>> x = np.linspace(0, 10, 70)
>>> y = np.sin(x)
>>> spl = UnivariateSpline(x, y, k=4, s=0)

Now, differentiate the spline and find the zeros of the
derivative. (NB: `sproot` only works for order 3 splines, so we
fit an order 4 spline):

>>> spl.derivative().roots() / np.pi
array([ 0.50000001,  1.5       ,  2.49999998])

This agrees well with roots :math:`\pi/2 + n\pi` of `cos(x) = sin'(x)`.