def quad(func, a, b, args=(), full_output=<NUM_LIT:0>, epsabs=<NUM_LIT>, epsrel=<NUM_LIT>,<EOL>limit=<NUM_LIT:50>, points=None, weight=None, wvar=None, wopts=None, maxp1=<NUM_LIT:50>,<EOL>limlst=<NUM_LIT:50>):

if not isinstance(args, tuple):<EOL><INDENT>args = (args,)<EOL><DEDENT>if (weight is None):<EOL><INDENT>retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,<EOL>points)<EOL><DEDENT>else:<EOL><INDENT>retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,<EOL>limlst, limit, maxp1, weight, wvar, wopts)<EOL><DEDENT>ier = retval[-<NUM_LIT:1>]<EOL>if ier == <NUM_LIT:0>:<EOL><INDENT>return retval[:-<NUM_LIT:1>]<EOL><DEDENT>msgs = {<NUM_LIT>: "<STR_LIT>",<EOL><NUM_LIT:1>: "<STR_LIT>" % limit,<EOL><NUM_LIT:2>: "<STR_LIT>",<EOL><NUM_LIT:3>: "<STR_LIT>",<EOL><NUM_LIT:4>: "<STR_LIT>",<EOL><NUM_LIT:5>: "<STR_LIT>",<EOL><NUM_LIT:6>: "<STR_LIT>",<EOL><NUM_LIT:7>: "<STR_LIT>",<EOL>'<STR_LIT>': "<STR_LIT>"}<EOL>if weight in ['<STR_LIT>','<STR_LIT>'] and (b == Inf or a == -Inf):<EOL><INDENT>msgs[<NUM_LIT:1>] = "<STR_LIT>"<EOL>msgs[<NUM_LIT:4>] = "<STR_LIT>"<EOL>msgs[<NUM_LIT:7>] = "<STR_LIT>"<EOL>explain = {<NUM_LIT:1>: "<STR_LIT>",<EOL><NUM_LIT:2>: "<STR_LIT>",<EOL><NUM_LIT:3>: "<STR_LIT>",<EOL><NUM_LIT:4>: "<STR_LIT>",<EOL><NUM_LIT:5>: "<STR_LIT>"}<EOL><DEDENT>try:<EOL><INDENT>msg = msgs[ier]<EOL><DEDENT>except KeyError:<EOL><INDENT>msg = msgs['<STR_LIT>']<EOL><DEDENT>if ier in [<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:3>,<NUM_LIT:4>,<NUM_LIT:5>,<NUM_LIT:7>]:<EOL><INDENT>if full_output:<EOL><INDENT>if weight in ['<STR_LIT>','<STR_LIT>'] and (b == Inf or a == Inf):<EOL><INDENT>return retval[:-<NUM_LIT:1>] + (msg, explain)<EOL><DEDENT>else:<EOL><INDENT>return retval[:-<NUM_LIT:1>] + (msg,)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>warnings.warn(msg, IntegrationWarning)<EOL>return retval[:-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError(msg)<EOL><DEDENT>

Compute a definite integral.

Integrate func from `a` to `b` (possibly infinite interval) using a
technique from the Fortran library QUADPACK.

Parameters
----------
func : function
    A Python function or method to integrate.  If `func` takes many
    arguments, it is integrated along the axis corresponding to the
    first argument.
    If the user desires improved integration performance, then f may
    instead be a ``ctypes`` function of the form:

        f(int n, double args[n]),

    where ``args`` is an array of function arguments and ``n`` is the
    length of ``args``. ``f.argtypes`` should be set to
    ``(c_int, c_double)``, and ``f.restype`` should be ``(c_double,)``.
a : float
    Lower limit of integration (use -numpy.inf for -infinity).
b : float
    Upper limit of integration (use numpy.inf for +infinity).
args : tuple, optional
    Extra arguments to pass to `func`.
full_output : int, optional
    Non-zero to return a dictionary of integration information.
    If non-zero, warning messages are also suppressed and the
    message is appended to the output tuple.

Returns
-------
y : float
    The integral of func from `a` to `b`.
abserr : float
    An estimate of the absolute error in the result.
infodict : dict
    A dictionary containing additional information.
    Run scipy.integrate.quad_explain() for more information.
message :
    A convergence message.
explain :
    Appended only with 'cos' or 'sin' weighting and infinite
    integration limits, it contains an explanation of the codes in
    infodict['ierlst']

Other Parameters
----------------
epsabs : float or int, optional
    Absolute error tolerance.
epsrel : float or int, optional
    Relative error tolerance.
limit : float or int, optional
    An upper bound on the number of subintervals used in the adaptive
    algorithm.
points : (sequence of floats,ints), optional
    A sequence of break points in the bounded integration interval
    where local difficulties of the integrand may occur (e.g.,
    singularities, discontinuities). The sequence does not have
    to be sorted.
weight : float or int, optional
    String indicating weighting function. Full explanation for this
    and the remaining arguments can be found below.
wvar : optional
    Variables for use with weighting functions.
wopts : optional
    Optional input for reusing Chebyshev moments.
maxp1 : float or int, optional
    An upper bound on the number of Chebyshev moments.
limlst : int, optional
    Upper bound on the number of cycles (>=3) for use with a sinusoidal
    weighting and an infinite end-point.

See Also
--------
dblquad : double integral
tplquad : triple integral
nquad : n-dimensional integrals (uses `quad` recursively)
fixed_quad : fixed-order Gaussian quadrature
quadrature : adaptive Gaussian quadrature
odeint : ODE integrator
ode : ODE integrator
simps : integrator for sampled data
romb : integrator for sampled data
scipy.special : for coefficients and roots of orthogonal polynomials

Notes
-----

**Extra information for quad() inputs and outputs**

If full_output is non-zero, then the third output argument
(infodict) is a dictionary with entries as tabulated below.  For
infinite limits, the range is transformed to (0,1) and the
optional outputs are given with respect to this transformed range.
Let M be the input argument limit and let K be infodict['last'].
The entries are:

'neval'
    The number of function evaluations.
'last'
    The number, K, of subintervals produced in the subdivision process.
'alist'
    A rank-1 array of length M, the first K elements of which are the
    left end points of the subintervals in the partition of the
    integration range.
'blist'
    A rank-1 array of length M, the first K elements of which are the
    right end points of the subintervals.
'rlist'
    A rank-1 array of length M, the first K elements of which are the
    integral approximations on the subintervals.
'elist'
    A rank-1 array of length M, the first K elements of which are the
    moduli of the absolute error estimates on the subintervals.
'iord'
    A rank-1 integer array of length M, the first L elements of
    which are pointers to the error estimates over the subintervals
    with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the
    sequence ``infodict['iord']`` and let E be the sequence
    ``infodict['elist']``.  Then ``E[I[1]], ..., E[I[L]]`` forms a
    decreasing sequence.

If the input argument points is provided (i.e. it is not None),
the following additional outputs are placed in the output
dictionary.  Assume the points sequence is of length P.

'pts'
    A rank-1 array of length P+2 containing the integration limits
    and the break points of the intervals in ascending order.
    This is an array giving the subintervals over which integration
    will occur.
'level'
    A rank-1 integer array of length M (=limit), containing the
    subdivision levels of the subintervals, i.e., if (aa,bb) is a
    subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``
    are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l
    if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.
'ndin'
    A rank-1 integer array of length P+2.  After the first integration
    over the intervals (pts[1], pts[2]), the error estimates over some
    of the intervals may have been increased artificially in order to
    put their subdivision forward.  This array has ones in slots
    corresponding to the subintervals for which this happens.

**Weighting the integrand**

The input variables, *weight* and *wvar*, are used to weight the
integrand by a select list of functions.  Different integration
methods are used to compute the integral with these weighting
functions.  The possible values of weight and the corresponding
weighting functions are.

==========  ===================================   =====================
``weight``  Weight function used                  ``wvar``
==========  ===================================   =====================
'cos'       cos(w*x)                              wvar = w
'sin'       sin(w*x)                              wvar = w
'alg'       g(x) = ((x-a)**alpha)*((b-x)**beta)   wvar = (alpha, beta)
'alg-loga'  g(x)*log(x-a)                         wvar = (alpha, beta)
'alg-logb'  g(x)*log(b-x)                         wvar = (alpha, beta)
'alg-log'   g(x)*log(x-a)*log(b-x)                wvar = (alpha, beta)
'cauchy'    1/(x-c)                               wvar = c
==========  ===================================   =====================

wvar holds the parameter w, (alpha, beta), or c depending on the weight
selected.  In these expressions, a and b are the integration limits.

For the 'cos' and 'sin' weighting, additional inputs and outputs are
available.

For finite integration limits, the integration is performed using a
Clenshaw-Curtis method which uses Chebyshev moments.  For repeated
calculations, these moments are saved in the output dictionary:

'momcom'
    The maximum level of Chebyshev moments that have been computed,
    i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been
    computed for intervals of length ``|b-a| * 2**(-l)``,
    ``l=0,1,...,M_c``.
'nnlog'
    A rank-1 integer array of length M(=limit), containing the
    subdivision levels of the subintervals, i.e., an element of this
    array is equal to l if the corresponding subinterval is
    ``|b-a|* 2**(-l)``.
'chebmo'
    A rank-2 array of shape (25, maxp1) containing the computed
    Chebyshev moments.  These can be passed on to an integration
    over the same interval by passing this array as the second
    element of the sequence wopts and passing infodict['momcom'] as
    the first element.

If one of the integration limits is infinite, then a Fourier integral is
computed (assuming w neq 0).  If full_output is 1 and a numerical error
is encountered, besides the error message attached to the output tuple,
a dictionary is also appended to the output tuple which translates the
error codes in the array ``info['ierlst']`` to English messages.  The
output information dictionary contains the following entries instead of
'last', 'alist', 'blist', 'rlist', and 'elist':

'lst'
    The number of subintervals needed for the integration (call it ``K_f``).
'rslst'
    A rank-1 array of length M_f=limlst, whose first ``K_f`` elements
    contain the integral contribution over the interval
    ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``
    and ``k=1,2,...,K_f``.
'erlst'
    A rank-1 array of length ``M_f`` containing the error estimate
    corresponding to the interval in the same position in
    ``infodict['rslist']``.
'ierlst'
    A rank-1 integer array of length ``M_f`` containing an error flag
    corresponding to the interval in the same position in
    ``infodict['rslist']``.  See the explanation dictionary (last entry
    in the output tuple) for the meaning of the codes.

Examples
--------
Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result

>>> from scipy import integrate
>>> x2 = lambda x: x**2
>>> integrate.quad(x2, 0, 4)
(21.333333333333332, 2.3684757858670003e-13)
>>> print(4**3 / 3.)  # analytical result
21.3333333333

Calculate :math:`\\int^\\infty_0 e^{-x} dx`

>>> invexp = lambda x: np.exp(-x)
>>> integrate.quad(invexp, 0, np.inf)
(1.0, 5.842605999138044e-11)

>>> f = lambda x,a : a*x
>>> y, err = integrate.quad(f, 0, 1, args=(1,))
>>> y
0.5
>>> y, err = integrate.quad(f, 0, 1, args=(3,))
>>> y
1.5

Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding
y parameter as 1::

    testlib.c =>
        double func(int n, double args[n]){
            return args[0]*args[0] + args[1]*args[1];}
    compile to library testlib.*

>>> from scipy import integrate
>>> import ctypes
>>> lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
>>> lib.func.restype = ctypes.c_double
>>> lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
>>> integrate.quad(lib.func,0,1,(1))
(1.3333333333333333, 1.4802973661668752e-14)
>>> print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
1.3333333333333333


def dblquad(func, a, b, gfun, hfun, args=(), epsabs=<NUM_LIT>, epsrel=<NUM_LIT>):

return quad(_infunc, a, b, (func, gfun, hfun, args),<EOL>epsabs=epsabs, epsrel=epsrel)<EOL>

Compute a double integral.

Return the double (definite) integral of ``func(y, x)`` from ``x = a..b``
and ``y = gfun(x)..hfun(x)``.

Parameters
----------
func : callable
    A Python function or method of at least two variables: y must be the
    first argument and x the second argument.
(a,b) : tuple
    The limits of integration in x: `a` < `b`
gfun : callable
    The lower boundary curve in y which is a function taking a single
    floating point argument (x) and returning a floating point result: a
    lambda function can be useful here.
hfun : callable
    The upper boundary curve in y (same requirements as `gfun`).
args : sequence, optional
    Extra arguments to pass to `func`.
epsabs : float, optional
    Absolute tolerance passed directly to the inner 1-D quadrature
    integration. Default is 1.49e-8.
epsrel : float
    Relative tolerance of the inner 1-D integrals. Default is 1.49e-8.

Returns
-------
y : float
    The resultant integral.
abserr : float
    An estimate of the error.

See also
--------
quad : single integral
tplquad : triple integral
nquad : N-dimensional integrals
fixed_quad : fixed-order Gaussian quadrature
quadrature : adaptive Gaussian quadrature
odeint : ODE integrator
ode : ODE integrator
simps : integrator for sampled data
romb : integrator for sampled data
scipy.special : for coefficients and roots of orthogonal polynomials


def tplquad(func, a, b, gfun, hfun, qfun, rfun, args=(), epsabs=<NUM_LIT>,<EOL>epsrel=<NUM_LIT>):

return dblquad(_infunc2, a, b, gfun, hfun, (func, qfun, rfun, args),<EOL>epsabs=epsabs, epsrel=epsrel)<EOL>

Compute a triple (definite) integral.

Return the triple integral of ``func(z, y, x)`` from ``x = a..b``,
``y = gfun(x)..hfun(x)``, and ``z = qfun(x,y)..rfun(x,y)``.

Parameters
----------
func : function
    A Python function or method of at least three variables in the
    order (z, y, x).
(a,b) : tuple
    The limits of integration in x: `a` < `b`
gfun : function
    The lower boundary curve in y which is a function taking a single
    floating point argument (x) and returning a floating point result:
    a lambda function can be useful here.
hfun : function
    The upper boundary curve in y (same requirements as `gfun`).
qfun : function
    The lower boundary surface in z.  It must be a function that takes
    two floats in the order (x, y) and returns a float.
rfun : function
    The upper boundary surface in z. (Same requirements as `qfun`.)
args : Arguments
    Extra arguments to pass to `func`.
epsabs : float, optional
    Absolute tolerance passed directly to the innermost 1-D quadrature
    integration. Default is 1.49e-8.
epsrel : float, optional
    Relative tolerance of the innermost 1-D integrals. Default is 1.49e-8.

Returns
-------
y : float
    The resultant integral.
abserr : float
    An estimate of the error.

See Also
--------
quad: Adaptive quadrature using QUADPACK
quadrature: Adaptive Gaussian quadrature
fixed_quad: Fixed-order Gaussian quadrature
dblquad: Double integrals
nquad : N-dimensional integrals
romb: Integrators for sampled data
simps: Integrators for sampled data
ode: ODE integrators
odeint: ODE integrators
scipy.special: For coefficients and roots of orthogonal polynomials


def nquad(func, ranges, args=None, opts=None):

depth = len(ranges)<EOL>ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges]<EOL>if args is None:<EOL><INDENT>args = ()<EOL><DEDENT>if opts is None:<EOL><INDENT>opts = [dict([])] * depth<EOL><DEDENT>if isinstance(opts, dict):<EOL><INDENT>opts = [opts] * depth<EOL><DEDENT>else:<EOL><INDENT>opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts]<EOL><DEDENT>return _NQuad(func, ranges, opts).integrate(*args)<EOL>

Integration over multiple variables.

Wraps `quad` to enable integration over multiple variables.
Various options allow improved integration of discontinuous functions, as
well as the use of weighted integration, and generally finer control of the
integration process.

Parameters
----------
func : callable
    The function to be integrated. Has arguments of ``x0, ... xn``,
    ``t0, tm``, where integration is carried out over ``x0, ... xn``, which
    must be floats.  Function signature should be
    ``func(x0, x1, ..., xn, t0, t1, ..., tm)``.  Integration is carried out
    in order.  That is, integration over ``x0`` is the innermost integral,
    and ``xn`` is the outermost.
    If performance is a concern, this function may be a ctypes function of
    the form::

        f(int n, double args[n])

    where ``n`` is the number of extra parameters and args is an array
    of doubles of the additional parameters.  This function may then
    be compiled to a dynamic/shared library then imported through
    ``ctypes``, setting the function's argtypes to ``(c_int, c_double)``,
    and the function's restype to ``(c_double)``.  Its pointer may then be
    passed into `nquad` normally.
    This allows the underlying Fortran library to evaluate the function in
    the innermost integration calls without callbacks to Python, and also
    speeds up the evaluation of the function itself.
ranges : iterable object
    Each element of ranges may be either a sequence  of 2 numbers, or else
    a callable that returns such a sequence.  ``ranges[0]`` corresponds to
    integration over x0, and so on.  If an element of ranges is a callable,
    then it will be called with all of the integration arguments available.
    e.g. if ``func = f(x0, x1, x2)``, then ``ranges[0]`` may be defined as
    either ``(a, b)`` or else as ``(a, b) = range0(x1, x2)``.
args : iterable object, optional
    Additional arguments ``t0, ..., tn``, required by `func`.
opts : iterable object or dict, optional
    Options to be passed to `quad`.  May be empty, a dict, or
    a sequence of dicts or functions that return a dict.  If empty, the
    default options from scipy.integrate.quadare used.  If a dict, the same
    options are used for all levels of integraion.  If a sequence, then each
    element of the sequence corresponds to a particular integration. e.g.
    opts[0] corresponds to integration over x0, and so on. The available
    options together with their default values are:

      - epsabs = 1.49e-08
      - epsrel = 1.49e-08
      - limit  = 50
      - points = None
      - weight = None
      - wvar   = None
      - wopts  = None

    The ``full_output`` option from `quad` is unavailable, due to the
    complexity of handling the large amount of data such an option would
    return for this kind of nested integration.  For more information on
    these options, see `quad` and `quad_explain`.

Returns
-------
result : float
    The result of the integration.
abserr : float
    The maximum of the estimates of the absolute error in the various
    integration results.

See Also
--------
quad : 1-dimensional numerical integration
dblquad, tplquad : double and triple integrals
fixed_quad : fixed-order Gaussian quadrature
quadrature : adaptive Gaussian quadrature

Examples
--------
>>> from scipy import integrate
>>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + (
...                                 1 if (x0-.2*x3-.5-.25*x1>0) else 0)
>>> points = [[lambda (x1,x2,x3) : 0.2*x3 + 0.5 + 0.25*x1], [], [], []]
>>> def opts0(*args, **kwargs):
...     return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]}
>>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]],
...                 opts=[opts0,{},{},{}])
(1.5267454070738633, 2.9437360001402324e-14)

>>> scale = .1
>>> def func2(x0, x1, x2, x3, t0, t1):
...     return x0*x1*x3**2 + np.sin(x2) + 1 + (1 if x0+t1*x1-t0>0 else 0)
>>> def lim0(x1, x2, x3, t0, t1):
...     return [scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) - 1,
...             scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) + 1]
>>> def lim1(x2, x3, t0, t1):
...     return [scale * (t0*x2 + t1*x3) - 1,
...             scale * (t0*x2 + t1*x3) + 1]
>>> def lim2(x3, t0, t1):
...     return [scale * (x3 + t0**2*t1**3) - 1,
...             scale * (x3 + t0**2*t1**3) + 1]
>>> def lim3(t0, t1):
...     return [scale * (t0+t1) - 1, scale * (t0+t1) + 1]
>>> def opts0(x1, x2, x3, t0, t1):
...     return {'points' : [t0 - t1*x1]}
>>> def opts1(x2, x3, t0, t1):
...     return {}
>>> def opts2(x3, t0, t1):
...     return {}
>>> def opts3(t0, t1):
...     return {}
>>> integrate.nquad(func2, [lim0, lim1, lim2, lim3], args=(0,0),
                    opts=[opts0, opts1, opts2, opts3])
(25.066666666666666, 2.7829590483937256e-13)


return self.range_<EOL>

Return stored value.

        *args needed because range_ can be float or func, and is called with
        variable number of parameters.


return self.opt<EOL>


def odeint(func, y0, t, args=(), Dfun=None, col_deriv=<NUM_LIT:0>, full_output=<NUM_LIT:0>,<EOL>ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=<NUM_LIT:0.0>,<EOL>hmax=<NUM_LIT:0.0>, hmin=<NUM_LIT:0.0>, ixpr=<NUM_LIT:0>, mxstep=<NUM_LIT:0>, mxhnil=<NUM_LIT:0>, mxordn=<NUM_LIT:12>,<EOL>mxords=<NUM_LIT:5>, printmessg=<NUM_LIT:0>):

if ml is None:<EOL><INDENT>ml = -<NUM_LIT:1>  <EOL><DEDENT>if mu is None:<EOL><INDENT>mu = -<NUM_LIT:1>  <EOL><DEDENT>t = copy(t)<EOL>y0 = copy(y0)<EOL>output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,<EOL>full_output, rtol, atol, tcrit, h0, hmax, hmin,<EOL>ixpr, mxstep, mxhnil, mxordn, mxords)<EOL>if output[-<NUM_LIT:1>] < <NUM_LIT:0>:<EOL><INDENT>print(_msgs[output[-<NUM_LIT:1>]])<EOL>print("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>if printmessg:<EOL><INDENT>print(_msgs[output[-<NUM_LIT:1>]])<EOL><DEDENT><DEDENT>if full_output:<EOL><INDENT>output[<NUM_LIT:1>]['<STR_LIT:message>'] = _msgs[output[-<NUM_LIT:1>]]<EOL><DEDENT>output = output[:-<NUM_LIT:1>]<EOL>if len(output) == <NUM_LIT:1>:<EOL><INDENT>return output[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return output<EOL><DEDENT>

Integrate a system of ordinary differential equations.

Solve a system of ordinary differential equations using lsoda from the
FORTRAN library odepack.

Solves the initial value problem for stiff or non-stiff systems
of first order ode-s::

    dy/dt = func(y,t0,...)

where y can be a vector.

Parameters
----------
func : callable(y, t0, ...)
    Computes the derivative of y at t0.
y0 : array
    Initial condition on y (can be a vector).
t : array
    A sequence of time points for which to solve for y.  The initial
    value point should be the first element of this sequence.
args : tuple, optional
    Extra arguments to pass to function.
Dfun : callable(y, t0, ...)
    Gradient (Jacobian) of `func`.
col_deriv : bool, optional
    True if `Dfun` defines derivatives down columns (faster),
    otherwise `Dfun` should define derivatives across rows.
full_output : bool, optional
    True if to return a dictionary of optional outputs as the second output
printmessg : bool, optional
    Whether to print the convergence message

Returns
-------
y : array, shape (len(t), len(y0))
    Array containing the value of y for each desired time in t,
    with the initial value `y0` in the first row.
infodict : dict, only returned if full_output == True
    Dictionary containing additional output information

    =======  ============================================================
    key      meaning
    =======  ============================================================
    'hu'     vector of step sizes successfully used for each time step.
    'tcur'   vector with the value of t reached for each time step.
             (will always be at least as large as the input times).
    'tolsf'  vector of tolerance scale factors, greater than 1.0,
             computed when a request for too much accuracy was detected.
    'tsw'    value of t at the time of the last method switch
             (given for each time step)
    'nst'    cumulative number of time steps
    'nfe'    cumulative number of function evaluations for each time step
    'nje'    cumulative number of jacobian evaluations for each time step
    'nqu'    a vector of method orders for each successful step.
    'imxer'  index of the component of largest magnitude in the
             weighted local error vector (e / ewt) on an error return, -1
             otherwise.
    'lenrw'  the length of the double work array required.
    'leniw'  the length of integer work array required.
    'mused'  a vector of method indicators for each successful time step:
             1: adams (nonstiff), 2: bdf (stiff)
    =======  ============================================================

Other Parameters
----------------
ml, mu : int, optional
    If either of these are not None or non-negative, then the
    Jacobian is assumed to be banded.  These give the number of
    lower and upper non-zero diagonals in this banded matrix.
    For the banded case, `Dfun` should return a matrix whose
    rows contain the non-zero bands (starting with the lowest diagonal).
    Thus, the return matrix `jac` from `Dfun` should have shape
    ``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
    The data in `jac` must be stored such that ``jac[i - j + mu, j]``
    holds the derivative of the `i`th equation with respect to the `j`th
    state variable.  If `col_deriv` is True, the transpose of this
    `jac` must be returned.
rtol, atol : float, optional
    The input parameters `rtol` and `atol` determine the error
    control performed by the solver.  The solver will control the
    vector, e, of estimated local errors in y, according to an
    inequality of the form ``max-norm of (e / ewt) <= 1``,
    where ewt is a vector of positive error weights computed as
    ``ewt = rtol * abs(y) + atol``.
    rtol and atol can be either vectors the same length as y or scalars.
    Defaults to 1.49012e-8.
tcrit : ndarray, optional
    Vector of critical points (e.g. singularities) where integration
    care should be taken.
h0 : float, (0: solver-determined), optional
    The step size to be attempted on the first step.
hmax : float, (0: solver-determined), optional
    The maximum absolute step size allowed.
hmin : float, (0: solver-determined), optional
    The minimum absolute step size allowed.
ixpr : bool, optional
    Whether to generate extra printing at method switches.
mxstep : int, (0: solver-determined), optional
    Maximum number of (internally defined) steps allowed for each
    integration point in t.
mxhnil : int, (0: solver-determined), optional
    Maximum number of messages printed.
mxordn : int, (0: solver-determined), optional
    Maximum order to be allowed for the non-stiff (Adams) method.
mxords : int, (0: solver-determined), optional
    Maximum order to be allowed for the stiff (BDF) method.

See Also
--------
ode : a more object-oriented integrator based on VODE.
quad : for finding the area under a curve.


def _gen_ridge_line(start_locs, max_locs, length, distances, gaps):

def keep_bounds(num, max_val):<EOL><INDENT>out = max(num, <NUM_LIT:0>)<EOL>out = min(out, max_val)<EOL>return out<EOL><DEDENT>gaps = copy.deepcopy(gaps)<EOL>distances = copy.deepcopy(distances)<EOL>locs = np.zeros([length, <NUM_LIT:2>], dtype=int)<EOL>locs[<NUM_LIT:0>, :] = start_locs<EOL>total_length = max_locs[<NUM_LIT:0>] - start_locs[<NUM_LIT:0>] - sum(gaps)<EOL>if total_length < length:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>dist_int = length / len(distances) - <NUM_LIT:1><EOL>gap_int = length / len(gaps) - <NUM_LIT:1><EOL>for ind in xrange(<NUM_LIT:1>, length):<EOL><INDENT>nextcol = locs[ind - <NUM_LIT:1>, <NUM_LIT:1>]<EOL>nextrow = locs[ind - <NUM_LIT:1>, <NUM_LIT:0>] + <NUM_LIT:1><EOL>if (ind % dist_int == <NUM_LIT:0>) and (len(distances) > <NUM_LIT:0>):<EOL><INDENT>nextcol += ((-<NUM_LIT:1>)**ind)*distances.pop()<EOL><DEDENT>if (ind % gap_int == <NUM_LIT:0>) and (len(gaps) > <NUM_LIT:0>):<EOL><INDENT>nextrow += gaps.pop()<EOL><DEDENT>nextrow = keep_bounds(nextrow, max_locs[<NUM_LIT:0>])<EOL>nextcol = keep_bounds(nextcol, max_locs[<NUM_LIT:1>])<EOL>locs[ind, :] = [nextrow, nextcol]<EOL><DEDENT>return [locs[:, <NUM_LIT:0>], locs[:, <NUM_LIT:1>]]<EOL>

Generate coordinates for a ridge line.

Will be a series of coordinates, starting a start_loc (length 2).
The maximum distance between any adjacent columns will be
`max_distance`, the max distance between adjacent rows
will be `map_gap'.

`max_locs` should be the size of the intended matrix. The
ending coordinates are guaranteed to be less than `max_locs`,
although they may not approach `max_locs` at all.


def alt_sg_coeffs(window_length, polyorder, pos):

if pos is None:<EOL><INDENT>pos = window_length // <NUM_LIT:2><EOL><DEDENT>t = np.arange(window_length)<EOL>unit = (t == pos).astype(int)<EOL>h = np.polyval(np.polyfit(t, unit, polyorder), t)<EOL>return h<EOL>

This is an alternative implementation of the SG coefficients.

    It uses numpy.polyfit and numpy.polyval.  The results should be
    equivalent to those of savgol_coeffs(), but this implementation
    is slower.

    window_length should be odd.


<EOL>dt = t[<NUM_LIT:1>] - t[<NUM_LIT:0>]<EOL>f = np.diff(theta)/(<NUM_LIT:2>*np.pi) / dt<EOL>tf = <NUM_LIT:0.5>*(t[<NUM_LIT:1>:] + t[:-<NUM_LIT:1>])<EOL>return tf, f<EOL>

Compute theta'(t)/(2*pi), where theta'(t) is the derivative of theta(t).


w, H = freqz(h, worN=<NUM_LIT>)<EOL>f = w/np.pi<EOL>passIndicator = np.zeros(len(w), bool)<EOL>for left, right in bands:<EOL><INDENT>passIndicator |= (f >= left) & (f < right)<EOL><DEDENT>Hideal = np.where(passIndicator, <NUM_LIT:1>, <NUM_LIT:0>)<EOL>mse = np.mean(abs(abs(H)-Hideal)**<NUM_LIT:2>)<EOL>return mse<EOL>

Compute mean squared error versus ideal response across frequency
        band.
          h -- coefficients
          bands -- list of (left, right) tuples relative to 1==Nyquist of
            passbands


def periodogram(x, fs=<NUM_LIT:1.0>, window=None, nfft=None, detrend='<STR_LIT>',<EOL>return_onesided=True, scaling='<STR_LIT>', axis=-<NUM_LIT:1>):

x = np.asarray(x)<EOL>if x.size == <NUM_LIT:0>:<EOL><INDENT>return np.empty(x.shape), np.empty(x.shape)<EOL><DEDENT>if window is None:<EOL><INDENT>window = '<STR_LIT>'<EOL><DEDENT>if nfft is None:<EOL><INDENT>nperseg = x.shape[axis]<EOL><DEDENT>elif nfft == x.shape[axis]:<EOL><INDENT>nperseg = nfft<EOL><DEDENT>elif nfft > x.shape[axis]:<EOL><INDENT>nperseg = x.shape[axis]<EOL><DEDENT>elif nfft < x.shape[axis]:<EOL><INDENT>s = [np.s_[:]]*len(x.shape)<EOL>s[axis] = np.s_[:nfft]<EOL>x = x[s]<EOL>nperseg = nfft<EOL>nfft = None<EOL><DEDENT>return welch(x, fs, window, nperseg, <NUM_LIT:0>, nfft, detrend, return_onesided,<EOL>scaling, axis)<EOL>

Estimate power spectral density using a periodogram.

Parameters
----------
x : array_like
    Time series of measurement values
fs : float, optional
    Sampling frequency of the `x` time series in units of Hz. Defaults
    to 1.0.
window : str or tuple or array_like, optional
    Desired window to use. See `get_window` for a list of windows and
    required parameters. If `window` is an array it will be used
    directly as the window. Defaults to None; equivalent to 'boxcar'.
nfft : int, optional
    Length of the FFT used. If None the length of `x` will be used.
detrend : str or function or False, optional
    Specifies how to detrend `x` prior to computing the spectrum. If
    `detrend` is a string, it is passed as the ``type`` argument to
    `detrend`.  If it is a function, it should return a detrended array.
    If `detrend` is False, no detrending is done.  Defaults to 'constant'.
return_onesided : bool, optional
    If True, return a one-sided spectrum for real data. If False return
    a two-sided spectrum. Note that for complex data, a two-sided
    spectrum is always returned.
scaling : { 'density', 'spectrum' }, optional
    Selects between computing the power spectral density ('density')
    where `Pxx` has units of V**2/Hz if `x` is measured in V and computing
    the power spectrum ('spectrum') where `Pxx` has units of V**2 if `x` is
    measured in V. Defaults to 'density'
axis : int, optional
    Axis along which the periodogram is computed; the default is over
    the last axis (i.e. ``axis=-1``).

Returns
-------
f : ndarray
    Array of sample frequencies.
Pxx : ndarray
    Power spectral density or power spectrum of `x`.

Notes
-----
.. versionadded:: 0.12.0

See Also
--------
welch: Estimate power spectral density using Welch's method
lombscargle: Lomb-Scargle periodogram for unevenly sampled data

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

Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by
0.001 V**2/Hz of white noise sampled at 10 kHz.

>>> fs = 10e3
>>> N = 1e5
>>> amp = 2*np.sqrt(2)
>>> freq = 1234.0
>>> noise_power = 0.001 * fs / 2
>>> time = np.arange(N) / fs
>>> x = amp*np.sin(2*np.pi*freq*time)
>>> x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)

Compute and plot the power spectral density.

>>> f, Pxx_den = signal.periodogram(x, fs)
>>> plt.semilogy(f, Pxx_den)
>>> plt.ylim([1e-7, 1e2])
>>> plt.xlabel('frequency [Hz]')
>>> plt.ylabel('PSD [V**2/Hz]')
>>> plt.show()

If we average the last half of the spectral density, to exclude the
peak, we can recover the noise power on the signal.

>>> np.mean(Pxx_den[256:])
0.0009924865443739191

Now compute and plot the power spectrum.

>>> f, Pxx_spec = signal.periodogram(x, fs, 'flattop', scaling='spectrum')
>>> plt.figure()
>>> plt.semilogy(f, np.sqrt(Pxx_spec))
>>> plt.ylim([1e-4, 1e1])
>>> plt.xlabel('frequency [Hz]')
>>> plt.ylabel('Linear spectrum [V RMS]')
>>> plt.show()

The peak height in the power spectrum is an estimate of the RMS amplitude.

>>> np.sqrt(Pxx_spec.max())
2.0077340678640727


def welch(x, fs=<NUM_LIT:1.0>, window='<STR_LIT>', nperseg=<NUM_LIT>, noverlap=None, nfft=None,<EOL>detrend='<STR_LIT>', return_onesided=True, scaling='<STR_LIT>', axis=-<NUM_LIT:1>):

x = np.asarray(x)<EOL>if x.size == <NUM_LIT:0>:<EOL><INDENT>return np.empty(x.shape), np.empty(x.shape)<EOL><DEDENT>if axis != -<NUM_LIT:1>:<EOL><INDENT>x = np.rollaxis(x, axis, len(x.shape))<EOL><DEDENT>if x.shape[-<NUM_LIT:1>] < nperseg:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>% (nperseg, axis, x.shape[axis], axis))<EOL>nperseg = x.shape[-<NUM_LIT:1>]<EOL><DEDENT>if isinstance(window, string_types) or type(window) is tuple:<EOL><INDENT>win = get_window(window, nperseg)<EOL><DEDENT>else:<EOL><INDENT>win = np.asarray(window)<EOL>if len(win.shape) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if win.shape[<NUM_LIT:0>] > x.shape[-<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>nperseg = win.shape[<NUM_LIT:0>]<EOL><DEDENT>outdtype = (np.array([x[<NUM_LIT:0>]]) * np.array([<NUM_LIT:1>], '<STR_LIT:f>')).dtype.char.lower()<EOL>if win.dtype != outdtype:<EOL><INDENT>win = win.astype(outdtype)<EOL><DEDENT>if scaling == '<STR_LIT>':<EOL><INDENT>scale = <NUM_LIT:1.0> / (fs * (win*win).sum())<EOL><DEDENT>elif scaling == '<STR_LIT>':<EOL><INDENT>scale = <NUM_LIT:1.0> / win.sum()**<NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % scaling)<EOL><DEDENT>if noverlap is None:<EOL><INDENT>noverlap = nperseg // <NUM_LIT:2><EOL><DEDENT>elif noverlap >= nperseg:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if nfft is None:<EOL><INDENT>nfft = nperseg<EOL><DEDENT>elif nfft < nperseg:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not detrend:<EOL><INDENT>detrend_func = lambda seg: seg<EOL><DEDENT>elif not hasattr(detrend, '<STR_LIT>'):<EOL><INDENT>detrend_func = lambda seg: signaltools.detrend(seg, type=detrend)<EOL><DEDENT>elif axis != -<NUM_LIT:1>:<EOL><INDENT>def detrend_func(seg):<EOL><INDENT>seg = np.rollaxis(seg, -<NUM_LIT:1>, axis)<EOL>seg = detrend(seg)<EOL>return np.rollaxis(seg, axis, len(seg.shape))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>detrend_func = detrend<EOL><DEDENT>step = nperseg - noverlap<EOL>indices = np.arange(<NUM_LIT:0>, x.shape[-<NUM_LIT:1>]-nperseg+<NUM_LIT:1>, step)<EOL>if np.isrealobj(x) and return_onesided:<EOL><INDENT>outshape = list(x.shape)<EOL>if nfft % <NUM_LIT:2> == <NUM_LIT:0>:  <EOL><INDENT>outshape[-<NUM_LIT:1>] = nfft // <NUM_LIT:2> + <NUM_LIT:1><EOL>Pxx = np.empty(outshape, outdtype)<EOL>for k, ind in enumerate(indices):<EOL><INDENT>x_dt = detrend_func(x[..., ind:ind+nperseg])<EOL>xft = fftpack.rfft(x_dt*win, nfft)<EOL>if k == <NUM_LIT:0>:<EOL><INDENT>Pxx[..., (<NUM_LIT:0>,-<NUM_LIT:1>)] = xft[..., (<NUM_LIT:0>,-<NUM_LIT:1>)]**<NUM_LIT:2><EOL>Pxx[..., <NUM_LIT:1>:-<NUM_LIT:1>] = xft[..., <NUM_LIT:1>:-<NUM_LIT:1>:<NUM_LIT:2>]**<NUM_LIT:2> + xft[..., <NUM_LIT:2>::<NUM_LIT:2>]**<NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>Pxx *= k/(k+<NUM_LIT:1.0>)<EOL>Pxx[..., (<NUM_LIT:0>,-<NUM_LIT:1>)] += xft[..., (<NUM_LIT:0>,-<NUM_LIT:1>)]**<NUM_LIT:2> / (k+<NUM_LIT:1.0>)<EOL>Pxx[..., <NUM_LIT:1>:-<NUM_LIT:1>] += (xft[..., <NUM_LIT:1>:-<NUM_LIT:1>:<NUM_LIT:2>]**<NUM_LIT:2> + xft[..., <NUM_LIT:2>::<NUM_LIT:2>]**<NUM_LIT:2>)/ (k+<NUM_LIT:1.0>)<EOL><DEDENT><DEDENT><DEDENT>else:  <EOL><INDENT>outshape[-<NUM_LIT:1>] = (nfft+<NUM_LIT:1>) // <NUM_LIT:2><EOL>Pxx = np.empty(outshape, outdtype)<EOL>for k, ind in enumerate(indices):<EOL><INDENT>x_dt = detrend_func(x[..., ind:ind+nperseg])<EOL>xft = fftpack.rfft(x_dt*win, nfft)<EOL>if k == <NUM_LIT:0>:<EOL><INDENT>Pxx[..., <NUM_LIT:0>] = xft[..., <NUM_LIT:0>]**<NUM_LIT:2><EOL>Pxx[..., <NUM_LIT:1>:] = xft[..., <NUM_LIT:1>::<NUM_LIT:2>]**<NUM_LIT:2> + xft[..., <NUM_LIT:2>::<NUM_LIT:2>]**<NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>Pxx *= k/(k+<NUM_LIT:1.0>)<EOL>Pxx[..., <NUM_LIT:0>] += xft[..., <NUM_LIT:0>]**<NUM_LIT:2> / (k+<NUM_LIT:1>)<EOL>Pxx[..., <NUM_LIT:1>:] += (xft[..., <NUM_LIT:1>::<NUM_LIT:2>]**<NUM_LIT:2> + xft[..., <NUM_LIT:2>::<NUM_LIT:2>]**<NUM_LIT:2>)/ (k+<NUM_LIT:1.0>)<EOL><DEDENT><DEDENT><DEDENT>Pxx[..., <NUM_LIT:1>:-<NUM_LIT:1>] *= <NUM_LIT:2>*scale<EOL>Pxx[..., (<NUM_LIT:0>,-<NUM_LIT:1>)] *= scale<EOL>f = np.arange(Pxx.shape[-<NUM_LIT:1>]) * (fs/nfft)<EOL><DEDENT>else:<EOL><INDENT>for k, ind in enumerate(indices):<EOL><INDENT>x_dt = detrend_func(x[..., ind:ind+nperseg])<EOL>xft = fftpack.fft(x_dt*win, nfft)<EOL>if k == <NUM_LIT:0>:<EOL><INDENT>Pxx = (xft * xft.conj()).real<EOL><DEDENT>else:<EOL><INDENT>Pxx *= k/(k+<NUM_LIT:1.0>)<EOL>Pxx += (xft * xft.conj()).real / (k+<NUM_LIT:1.0>)<EOL><DEDENT><DEDENT>Pxx *= scale<EOL>f = fftpack.fftfreq(nfft, <NUM_LIT:1.0>/fs)<EOL><DEDENT>if axis != -<NUM_LIT:1>:<EOL><INDENT>Pxx = np.rollaxis(Pxx, -<NUM_LIT:1>, axis)<EOL><DEDENT>return f, Pxx<EOL>

Estimate power spectral density using Welch's method.

Welch's method [1]_ computes an estimate of the power spectral density
by dividing the data into overlapping segments, computing a modified
periodogram for each segment and averaging the periodograms.

Parameters
----------
x : array_like
    Time series of measurement values
fs : float, optional
    Sampling frequency of the `x` time series in units of Hz. Defaults
    to 1.0.
window : str or tuple or array_like, optional
    Desired window to use. See `get_window` for a list of windows and
    required parameters. If `window` is array_like it will be used
    directly as the window and its length will be used for nperseg.
    Defaults to 'hanning'.
nperseg : int, optional
    Length of each segment.  Defaults to 256.
noverlap: int, optional
    Number of points to overlap between segments. If None,
    ``noverlap = nperseg / 2``.  Defaults to None.
nfft : int, optional
    Length of the FFT used, if a zero padded FFT is desired.  If None,
    the FFT length is `nperseg`. Defaults to None.
detrend : str or function or False, optional
    Specifies how to detrend each segment. If `detrend` is a string,
    it is passed as the ``type`` argument to `detrend`.  If it is a
    function, it takes a segment and returns a detrended segment.
    If `detrend` is False, no detrending is done.  Defaults to 'constant'.
return_onesided : bool, optional
    If True, return a one-sided spectrum for real data. If False return
    a two-sided spectrum. Note that for complex data, a two-sided
    spectrum is always returned.
scaling : { 'density', 'spectrum' }, optional
    Selects between computing the power spectral density ('density')
    where Pxx has units of V**2/Hz if x is measured in V and computing
    the power spectrum ('spectrum') where Pxx has units of V**2 if x is
    measured in V. Defaults to 'density'.
axis : int, optional
    Axis along which the periodogram is computed; the default is over
    the last axis (i.e. ``axis=-1``).

Returns
-------
f : ndarray
    Array of sample frequencies.
Pxx : ndarray
    Power spectral density or power spectrum of x.

See Also
--------
periodogram: Simple, optionally modified periodogram
lombscargle: Lomb-Scargle periodogram for unevenly sampled data

Notes
-----
An appropriate amount of overlap will depend on the choice of window
and on your requirements.  For the default 'hanning' window an
overlap of 50% is a reasonable trade off between accurately estimating
the signal power, while not over counting any of the data.  Narrower
windows may require a larger overlap.

If `noverlap` is 0, this method is equivalent to Bartlett's method [2]_.

.. versionadded:: 0.12.0

References
----------
.. [1] P. Welch, "The use of the fast Fourier transform for the
       estimation of power spectra: A method based on time averaging
       over short, modified periodograms", IEEE Trans. Audio
       Electroacoust. vol. 15, pp. 70-73, 1967.
.. [2] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
       Biometrika, vol. 37, pp. 1-16, 1950.

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

Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by
0.001 V**2/Hz of white noise sampled at 10 kHz.

>>> fs = 10e3
>>> N = 1e5
>>> amp = 2*np.sqrt(2)
>>> freq = 1234.0
>>> noise_power = 0.001 * fs / 2
>>> time = np.arange(N) / fs
>>> x = amp*np.sin(2*np.pi*freq*time)
>>> x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)

Compute and plot the power spectral density.

>>> f, Pxx_den = signal.welch(x, fs, nperseg=1024)
>>> plt.semilogy(f, Pxx_den)
>>> plt.ylim([0.5e-3, 1])
>>> plt.xlabel('frequency [Hz]')
>>> plt.ylabel('PSD [V**2/Hz]')
>>> plt.show()

If we average the last half of the spectral density, to exclude the
peak, we can recover the noise power on the signal.

>>> np.mean(Pxx_den[256:])
0.0009924865443739191

Now compute and plot the power spectrum.

>>> f, Pxx_spec = signal.welch(x, fs, 'flattop', 1024, scaling='spectrum')
>>> plt.figure()
>>> plt.semilogy(f, np.sqrt(Pxx_spec))
>>> plt.xlabel('frequency [Hz]')
>>> plt.ylabel('Linear spectrum [V RMS]')
>>> plt.show()

The peak height in the power spectrum is an estimate of the RMS amplitude.

>>> np.sqrt(Pxx_spec.max())
2.0077340678640727


<EOL>num, den = normalize(num, den)   <EOL>nn = len(num.shape)<EOL>if nn == <NUM_LIT:1>:<EOL><INDENT>num = asarray([num], num.dtype)<EOL><DEDENT>M = num.shape[<NUM_LIT:1>]<EOL>K = len(den)<EOL>if M > K:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>if M == <NUM_LIT:0> or K == <NUM_LIT:0>:  <EOL><INDENT>return array([], float), array([], float), array([], float),array([], float)<EOL><DEDENT>num = r_['<STR_LIT>', zeros((num.shape[<NUM_LIT:0>], K - M), num.dtype), num]<EOL>if num.shape[-<NUM_LIT:1>] > <NUM_LIT:0>:<EOL><INDENT>D = num[:, <NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>D = array([], float)<EOL><DEDENT>if K == <NUM_LIT:1>:<EOL><INDENT>return array([], float), array([], float), array([], float), D<EOL><DEDENT>frow = -array([den[<NUM_LIT:1>:]])<EOL>A = r_[frow, eye(K - <NUM_LIT:2>, K - <NUM_LIT:1>)]<EOL>B = eye(K - <NUM_LIT:1>, <NUM_LIT:1>)<EOL>C = num[:, <NUM_LIT:1>:] - num[:, <NUM_LIT:0>] * den[<NUM_LIT:1>:]<EOL>return A, B, C, D<EOL>

Transfer function to state-space representation.

    Parameters
    ----------
    num, den : array_like
        Sequences representing the numerator and denominator polynomials.
        The denominator needs to be at least as long as the numerator.

    Returns
    -------
    A, B, C, D : ndarray
        State space representation of the system, in controller canonical
        form.


def abcd_normalize(A=None, B=None, C=None, D=None):

A, B, C, D = map(_atleast_2d_or_none, (A, B, C, D))<EOL>MA, NA = _shape_or_none(A)<EOL>MB, NB = _shape_or_none(B)<EOL>MC, NC = _shape_or_none(C)<EOL>MD, ND = _shape_or_none(D)<EOL>p = _choice_not_none(MA, MB, NC)<EOL>q = _choice_not_none(NB, ND)<EOL>r = _choice_not_none(MC, MD)<EOL>if p is None or q is None or r is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>A, B, C, D = map(_none_to_empty_2d, (A, B, C, D))<EOL>A = _restore(A, (p, p))<EOL>B = _restore(B, (p, q))<EOL>C = _restore(C, (r, p))<EOL>D = _restore(D, (r, q))<EOL>return A, B, C, D<EOL>

Check state-space matrices and ensure they are two-dimensional.

    If enough information on the system is provided, that is, enough
    properly-shaped arrays are passed to the function, the missing ones
    are built from this information, ensuring the correct number of
    rows and columns. Otherwise a ValueError is raised.

    Parameters
    ----------
    A, B, C, D : array_like, optional
        State-space matrices. All of them are None (missing) by default.

    Returns
    -------
    A, B, C, D : array
        Properly shaped state-space matrices.

    Raises
    ------
    ValueError
        If not enough information on the system was provided.


def ss2tf(A, B, C, D, input=<NUM_LIT:0>):

<EOL>A, B, C, D = map(asarray, (A, B, C, D))<EOL>A, B, C, D = abcd_normalize(A, B, C, D)<EOL>nout, nin = D.shape<EOL>if input >= nin:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>B = B[:, input:input + <NUM_LIT:1>]<EOL>D = D[:, input:input + <NUM_LIT:1>]<EOL>try:<EOL><INDENT>den = poly(A)<EOL><DEDENT>except ValueError:<EOL><INDENT>den = <NUM_LIT:1><EOL><DEDENT>if (product(B.shape, axis=<NUM_LIT:0>) == <NUM_LIT:0>) and (product(C.shape, axis=<NUM_LIT:0>) == <NUM_LIT:0>):<EOL><INDENT>num = numpy.ravel(D)<EOL>if (product(D.shape, axis=<NUM_LIT:0>) == <NUM_LIT:0>) and (product(A.shape, axis=<NUM_LIT:0>) == <NUM_LIT:0>):<EOL><INDENT>den = []<EOL><DEDENT>return num, den<EOL><DEDENT>num_states = A.shape[<NUM_LIT:0>]<EOL>type_test = A[:, <NUM_LIT:0>] + B[:, <NUM_LIT:0>] + C[<NUM_LIT:0>, :] + D<EOL>num = numpy.zeros((nout, num_states + <NUM_LIT:1>), type_test.dtype)<EOL>for k in range(nout):<EOL><INDENT>Ck = atleast_2d(C[k, :])<EOL>num[k] = poly(A - dot(B, Ck)) + (D[k] - <NUM_LIT:1>) * den<EOL><DEDENT>return num, den<EOL>

State-space to transfer function.

    Parameters
    ----------
    A, B, C, D : ndarray
        State-space representation of linear system.
    input : int, optional
        For multiple-input systems, the input to use.

    Returns
    -------
    num : 2-D ndarray
        Numerator(s) of the resulting transfer function(s).  `num` has one row
        for each of the system's outputs. Each row is a sequence representation
        of the numerator polynomial.
    den : 1-D ndarray
        Denominator of the resulting transfer function(s).  `den` is a sequence
        representation of the denominator polynomial.


return tf2ss(*zpk2tf(z, p, k))<EOL>

Zero-pole-gain representation to state-space representation

    Parameters
    ----------
    z, p : sequence
        Zeros and poles.
    k : float
        System gain.

    Returns
    -------
    A, B, C, D : ndarray
        State space representation of the system, in controller canonical
        form.


def ss2zpk(A, B, C, D, input=<NUM_LIT:0>):

return tf2zpk(*ss2tf(A, B, C, D, input=input))<EOL>

State-space representation to zero-pole-gain representation.

    Parameters
    ----------
    A, B, C, D : ndarray
        State-space representation of linear system.
    input : int, optional
        For multiple-input systems, the input to use.

    Returns
    -------
    z, p : sequence
        Zeros and poles.
    k : float
        System gain.


def lsim2(system, U=None, T=None, X0=None, **kwargs):

if isinstance(system, lti):<EOL><INDENT>sys = system<EOL><DEDENT>else:<EOL><INDENT>sys = lti(*system)<EOL><DEDENT>if X0 is None:<EOL><INDENT>X0 = zeros(sys.B.shape[<NUM_LIT:0>], sys.A.dtype)<EOL><DEDENT>if T is None:<EOL><INDENT>T = linspace(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT>)<EOL><DEDENT>T = atleast_1d(T)<EOL>if len(T.shape) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if U is not None:<EOL><INDENT>U = atleast_1d(U)<EOL>if len(U.shape) == <NUM_LIT:1>:<EOL><INDENT>U = U.reshape(-<NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>sU = U.shape<EOL>if sU[<NUM_LIT:0>] != len(T):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if sU[<NUM_LIT:1>] != sys.inputs:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (sU[<NUM_LIT:1>], sys.inputs))<EOL><DEDENT>ufunc = interpolate.interp1d(T, U, kind='<STR_LIT>',<EOL>axis=<NUM_LIT:0>, bounds_error=False)<EOL>def fprime(x, t, sys, ufunc):<EOL><INDENT>"""<STR_LIT>"""<EOL>return dot(sys.A, x) + squeeze(dot(sys.B, nan_to_num(ufunc([t]))))<EOL><DEDENT>xout = integrate.odeint(fprime, X0, T, args=(sys, ufunc), **kwargs)<EOL>yout = dot(sys.C, transpose(xout)) + dot(sys.D, transpose(U))<EOL><DEDENT>else:<EOL><INDENT>def fprime(x, t, sys):<EOL><INDENT>"""<STR_LIT>"""<EOL>return dot(sys.A, x)<EOL><DEDENT>xout = integrate.odeint(fprime, X0, T, args=(sys,), **kwargs)<EOL>yout = dot(sys.C, transpose(xout))<EOL><DEDENT>return T, squeeze(transpose(yout)), xout<EOL>

Simulate output of a continuous-time linear system, by using
the ODE solver `scipy.integrate.odeint`.

Parameters
----------
system : an instance of the LTI class or a tuple describing the system.
    The following gives the number of elements in the tuple and
    the interpretation:

    * 2: (num, den)
    * 3: (zeros, poles, gain)
    * 4: (A, B, C, D)

U : array_like (1D or 2D), optional
    An input array describing the input at each time T.  Linear
    interpolation is used between given times.  If there are
    multiple inputs, then each column of the rank-2 array
    represents an input.  If U is not given, the input is assumed
    to be zero.
T : array_like (1D or 2D), optional
    The time steps at which the input is defined and at which the
    output is desired.  The default is 101 evenly spaced points on
    the interval [0,10.0].
X0 : array_like (1D), optional
    The initial condition of the state vector.  If `X0` is not
    given, the initial conditions are assumed to be 0.
kwargs : dict
    Additional keyword arguments are passed on to the function
    `odeint`.  See the notes below for more details.

Returns
-------
T : 1D ndarray
    The time values for the output.
yout : ndarray
    The response of the system.
xout : ndarray
    The time-evolution of the state-vector.

Notes
-----
This function uses `scipy.integrate.odeint` to solve the
system's differential equations.  Additional keyword arguments
given to `lsim2` are passed on to `odeint`.  See the documentation
for `scipy.integrate.odeint` for the full list of arguments.


if numpy.issubdtype(in2.dtype, numpy.float):<EOL><INDENT>in1 = in1.real.astype(in2.dtype)<EOL><DEDENT>else:<EOL><INDENT>in1 = in1.astype(in2.dtype)<EOL><DEDENT>return in1<EOL>

Cast array to dtype of other array, while avoiding ComplexWarning.

    Those can be raised when casting complex to real.


def lsim(system, U, T, X0=None, interp=<NUM_LIT:1>):

if isinstance(system, lti):<EOL><INDENT>sys = system<EOL><DEDENT>else:<EOL><INDENT>sys = lti(*system)<EOL><DEDENT>U = atleast_1d(U)<EOL>T = atleast_1d(T)<EOL>if len(U.shape) == <NUM_LIT:1>:<EOL><INDENT>U = U.reshape((U.shape[<NUM_LIT:0>], <NUM_LIT:1>))<EOL><DEDENT>sU = U.shape<EOL>if len(T.shape) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if sU[<NUM_LIT:0>] != len(T):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if sU[<NUM_LIT:1>] != sys.inputs:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if X0 is None:<EOL><INDENT>X0 = zeros(sys.B.shape[<NUM_LIT:0>], sys.A.dtype)<EOL><DEDENT>xout = zeros((len(T), sys.B.shape[<NUM_LIT:0>]), sys.A.dtype)<EOL>xout[<NUM_LIT:0>] = X0<EOL>A = sys.A<EOL>AT, BT = transpose(sys.A), transpose(sys.B)<EOL>dt = T[<NUM_LIT:1>] - T[<NUM_LIT:0>]<EOL>lam, v = linalg.eig(A)<EOL>vt = transpose(v)<EOL>vti = linalg.inv(vt)<EOL>GT = dot(dot(vti, diag(numpy.exp(dt * lam))), vt)<EOL>GT = _cast_to_array_dtype(GT, xout)<EOL>ATm1 = linalg.inv(AT)<EOL>ATm2 = dot(ATm1, ATm1)<EOL>I = eye(A.shape[<NUM_LIT:0>], dtype=A.dtype)<EOL>GTmI = GT - I<EOL>F1T = dot(dot(BT, GTmI), ATm1)<EOL>if interp:<EOL><INDENT>F2T = dot(BT, dot(GTmI, ATm2) / dt - ATm1)<EOL><DEDENT>for k in xrange(<NUM_LIT:1>, len(T)):<EOL><INDENT>dt1 = T[k] - T[k - <NUM_LIT:1>]<EOL>if dt1 != dt:<EOL><INDENT>dt = dt1<EOL>GT = dot(dot(vti, diag(numpy.exp(dt * lam))), vt)<EOL>GT = _cast_to_array_dtype(GT, xout)<EOL>GTmI = GT - I<EOL>F1T = dot(dot(BT, GTmI), ATm1)<EOL>if interp:<EOL><INDENT>F2T = dot(BT, dot(GTmI, ATm2) / dt - ATm1)<EOL><DEDENT><DEDENT>xout[k] = dot(xout[k - <NUM_LIT:1>], GT) + dot(U[k - <NUM_LIT:1>], F1T)<EOL>if interp:<EOL><INDENT>xout[k] = xout[k] + dot((U[k] - U[k - <NUM_LIT:1>]), F2T)<EOL><DEDENT><DEDENT>yout = (squeeze(dot(U, transpose(sys.D))) +<EOL>squeeze(dot(xout, transpose(sys.C))))<EOL>return T, squeeze(yout), squeeze(xout)<EOL>

Simulate output of a continuous-time linear system.

Parameters
----------
system : an instance of the LTI class or a tuple describing the system.
    The following gives the number of elements in the tuple and
    the interpretation:

    * 2: (num, den)
    * 3: (zeros, poles, gain)
    * 4: (A, B, C, D)

U : array_like
    An input array describing the input at each time `T`
    (interpolation is assumed between given times).  If there are
    multiple inputs, then each column of the rank-2 array
    represents an input.
T : array_like
    The time steps at which the input is defined and at which the
    output is desired.
X0 :
    The initial conditions on the state vector (zero by default).
interp : {1, 0}
    Whether to use linear (1) or zero-order hold (0) interpolation.

Returns
-------
T : 1D ndarray
    Time values for the output.
yout : 1D ndarray
    System response.
xout : ndarray
    Time-evolution of the state-vector.


<EOL>vals = linalg.eigvals(A)<EOL>r = min(abs(real(vals)))<EOL>if r == <NUM_LIT:0.0>:<EOL><INDENT>r = <NUM_LIT:1.0><EOL><DEDENT>tc = <NUM_LIT:1.0> / r<EOL>t = linspace(<NUM_LIT:0.0>, <NUM_LIT:7> * tc, n)<EOL>return t<EOL>

Compute a reasonable set of time samples for the response time.

    This function is used by `impulse`, `impulse2`, `step` and `step2`
    to compute the response time when the `T` argument to the function
    is None.

    Parameters
    ----------
    A : ndarray
        The system matrix, which is square.
    n : int
        The number of time samples to generate.

    Returns
    -------
    t : ndarray
        The 1-D array of length `n` of time samples at which the response
        is to be computed.


def impulse(system, X0=None, T=None, N=None):

if isinstance(system, lti):<EOL><INDENT>sys = system<EOL><DEDENT>else:<EOL><INDENT>sys = lti(*system)<EOL><DEDENT>if X0 is None:<EOL><INDENT>B = sys.B<EOL><DEDENT>else:<EOL><INDENT>B = sys.B + X0<EOL><DEDENT>if N is None:<EOL><INDENT>N = <NUM_LIT:100><EOL><DEDENT>if T is None:<EOL><INDENT>T = _default_response_times(sys.A, N)<EOL><DEDENT>else:<EOL><INDENT>T = asarray(T)<EOL><DEDENT>h = zeros(T.shape, sys.A.dtype)<EOL>s, v = linalg.eig(sys.A)<EOL>vi = linalg.inv(v)<EOL>C = sys.C<EOL>for k in range(len(h)):<EOL><INDENT>es = diag(numpy.exp(s * T[k]))<EOL>eA = dot(dot(v, es), vi)<EOL>eA = _cast_to_array_dtype(eA, h)<EOL>h[k] = squeeze(dot(dot(C, eA), B))<EOL><DEDENT>return T, h<EOL>

Impulse response of continuous-time system.

    Parameters
    ----------
    system : an instance of the LTI class or a tuple of array_like
        describing the system.
        The following gives the number of elements in the tuple and
        the interpretation:

            * 2 (num, den)
            * 3 (zeros, poles, gain)
            * 4 (A, B, C, D)

    X0 : array_like, optional
        Initial state-vector.  Defaults to zero.
    T : array_like, optional
        Time points.  Computed if not given.
    N : int, optional
        The number of time points to compute (if `T` is not given).

    Returns
    -------
    T : ndarray
        A 1-D array of time points.
    yout : ndarray
        A 1-D array containing the impulse response of the system (except for
        singularities at zero).


def impulse2(system, X0=None, T=None, N=None, **kwargs):

if isinstance(system, lti):<EOL><INDENT>sys = system<EOL><DEDENT>else:<EOL><INDENT>sys = lti(*system)<EOL><DEDENT>B = sys.B<EOL>if B.shape[-<NUM_LIT:1>] != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>B = B.squeeze()<EOL>if X0 is None:<EOL><INDENT>X0 = zeros_like(B)<EOL><DEDENT>if N is None:<EOL><INDENT>N = <NUM_LIT:100><EOL><DEDENT>if T is None:<EOL><INDENT>T = _default_response_times(sys.A, N)<EOL><DEDENT>ic = B + X0<EOL>Tr, Yr, Xr = lsim2(sys, T=T, X0=ic, **kwargs)<EOL>return Tr, Yr<EOL>

Impulse response of a single-input, continuous-time linear system.

Parameters
----------
system : an instance of the LTI class or a tuple of array_like
    describing the system.
    The following gives the number of elements in the tuple and
    the interpretation:

        * 2 (num, den)
        * 3 (zeros, poles, gain)
        * 4 (A, B, C, D)

X0 : 1-D array_like, optional
    The initial condition of the state vector.  Default: 0 (the
    zero vector).
T : 1-D array_like, optional
    The time steps at which the input is defined and at which the
    output is desired.  If `T` is not given, the function will
    generate a set of time samples automatically.
N : int, optional
    Number of time points to compute.  Default: 100.
kwargs : various types
    Additional keyword arguments are passed on to the function
    `scipy.signal.lsim2`, which in turn passes them on to
    `scipy.integrate.odeint`; see the latter's documentation for
    information about these arguments.

Returns
-------
T : ndarray
    The time values for the output.
yout : ndarray
    The output response of the system.

See Also
--------
impulse, lsim2, integrate.odeint

Notes
-----
The solution is generated by calling `scipy.signal.lsim2`, which uses
the differential equation solver `scipy.integrate.odeint`.

.. versionadded:: 0.8.0

Examples
--------
Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = u(t)

>>> from scipy import signal
>>> system = ([1.0], [1.0, 2.0, 1.0])
>>> t, y = signal.impulse2(system)
>>> import matplotlib.pyplot as plt
>>> plt.plot(t, y)


def step(system, X0=None, T=None, N=None):

if isinstance(system, lti):<EOL><INDENT>sys = system<EOL><DEDENT>else:<EOL><INDENT>sys = lti(*system)<EOL><DEDENT>if N is None:<EOL><INDENT>N = <NUM_LIT:100><EOL><DEDENT>if T is None:<EOL><INDENT>T = _default_response_times(sys.A, N)<EOL><DEDENT>else:<EOL><INDENT>T = asarray(T)<EOL><DEDENT>U = ones(T.shape, sys.A.dtype)<EOL>vals = lsim(sys, U, T, X0=X0)<EOL>return vals[<NUM_LIT:0>], vals[<NUM_LIT:1>]<EOL>

Step response of continuous-time system.

    Parameters
    ----------
    system : an instance of the LTI class or a tuple of array_like
        describing the system.
        The following gives the number of elements in the tuple and
        the interpretation:

            * 2 (num, den)
            * 3 (zeros, poles, gain)
            * 4 (A, B, C, D)

    X0 : array_like, optional
        Initial state-vector (default is zero).
    T : array_like, optional
        Time points (computed if not given).
    N : int
        Number of time points to compute if `T` is not given.

    Returns
    -------
    T : 1D ndarray
        Output time points.
    yout : 1D ndarray
        Step response of system.

    See also
    --------
    scipy.signal.step2


def step2(system, X0=None, T=None, N=None, **kwargs):

if isinstance(system, lti):<EOL><INDENT>sys = system<EOL><DEDENT>else:<EOL><INDENT>sys = lti(*system)<EOL><DEDENT>if N is None:<EOL><INDENT>N = <NUM_LIT:100><EOL><DEDENT>if T is None:<EOL><INDENT>T = _default_response_times(sys.A, N)<EOL><DEDENT>else:<EOL><INDENT>T = asarray(T)<EOL><DEDENT>U = ones(T.shape, sys.A.dtype)<EOL>vals = lsim2(sys, U, T, X0=X0, **kwargs)<EOL>return vals[<NUM_LIT:0>], vals[<NUM_LIT:1>]<EOL>

Step response of continuous-time system.

    This function is functionally the same as `scipy.signal.step`, but
    it uses the function `scipy.signal.lsim2` to compute the step
    response.

    Parameters
    ----------
    system : an instance of the LTI class or a tuple of array_like
        describing the system.
        The following gives the number of elements in the tuple and
        the interpretation:

            * 2 (num, den)
            * 3 (zeros, poles, gain)
            * 4 (A, B, C, D)

    X0 : array_like, optional
        Initial state-vector (default is zero).
    T : array_like, optional
        Time points (computed if not given).
    N : int
        Number of time points to compute if `T` is not given.
    kwargs : various types
        Additional keyword arguments are passed on the function
        `scipy.signal.lsim2`, which in turn passes them on to
        `scipy.integrate.odeint`.  See the documentation for
        `scipy.integrate.odeint` for information about these arguments.

    Returns
    -------
    T : 1D ndarray
        Output time points.
    yout : 1D ndarray
        Step response of system.

    See also
    --------
    scipy.signal.step

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


def bode(system, w=None, n=<NUM_LIT:100>):

w, y = freqresp(system, w=w, n=n)<EOL>mag = <NUM_LIT> * numpy.log10(abs(y))<EOL>phase = numpy.unwrap(numpy.arctan2(y.imag, y.real)) * <NUM_LIT> / numpy.pi<EOL>return w, mag, phase<EOL>

Calculate Bode magnitude and phase data of a continuous-time system.

Parameters
----------
system : an instance of the LTI class or a tuple describing the system.
    The following gives the number of elements in the tuple and
    the interpretation:

        * 2 (num, den)
        * 3 (zeros, poles, gain)
        * 4 (A, B, C, D)

w : array_like, optional
    Array of frequencies (in rad/s). Magnitude and phase data is calculated
    for every value in this array. If not given a reasonable set will be
    calculated.
n : int, optional
    Number of frequency points to compute if `w` is not given. The `n`
    frequencies are logarithmically spaced in an interval chosen to
    include the influence of the poles and zeros of the system.

Returns
-------
w : 1D ndarray
    Frequency array [rad/s]
mag : 1D ndarray
    Magnitude array [dB]
phase : 1D ndarray
    Phase array [deg]

Notes
-----

.. versionadded:: 0.11.0

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

>>> s1 = signal.lti([1], [1, 1])
>>> w, mag, phase = signal.bode(s1)

>>> plt.figure()
>>> plt.semilogx(w, mag)    # Bode magnitude plot
>>> plt.figure()
>>> plt.semilogx(w, phase)  # Bode phase plot
>>> plt.show()


def freqresp(system, w=None, n=<NUM_LIT>):

if isinstance(system, lti):<EOL><INDENT>sys = system<EOL><DEDENT>else:<EOL><INDENT>sys = lti(*system)<EOL><DEDENT>if sys.inputs != <NUM_LIT:1> or sys.outputs != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if w is not None:<EOL><INDENT>worN = w<EOL><DEDENT>else:<EOL><INDENT>worN = n<EOL><DEDENT>w, h = freqs(sys.num.ravel(), sys.den, worN=worN)<EOL>return w, h<EOL>

Calculate the frequency response of a continuous-time system.

    Parameters
    ----------
    system : an instance of the LTI class or a tuple describing the system.
        The following gives the number of elements in the tuple and
        the interpretation:

            * 2 (num, den)
            * 3 (zeros, poles, gain)
            * 4 (A, B, C, D)

    w : array_like, optional
        Array of frequencies (in rad/s). Magnitude and phase data is
        calculated for every value in this array. If not given a reasonable
        set will be calculated.
    n : int, optional
        Number of frequency points to compute if `w` is not given. The `n`
        frequencies are logarithmically spaced in an interval chosen to
        include the influence of the poles and zeros of the system.

    Returns
    -------
    w : 1D ndarray
        Frequency array [rad/s]
    H : 1D ndarray
        Array of complex magnitude values

    Examples
    --------
    # Generating the Nyquist plot of a transfer function

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

    >>> s1 = signal.lti([], [1, 1, 1], [5])
    # transfer function: H(s) = 5 / (s-1)^3

    >>> w, H = signal.freqresp(s1)

    >>> plt.figure()
    >>> plt.plot(H.real, H.imag, "b")
    >>> plt.plot(H.real, -H.imag, "r")
    >>> plt.show()


N = len(args)<EOL>if N == <NUM_LIT:2>:  <EOL><INDENT>self._num, self._den = normalize(*args)<EOL>self._update(N)<EOL>self.inputs = <NUM_LIT:1><EOL>if len(self.num.shape) > <NUM_LIT:1>:<EOL><INDENT>self.outputs = self.num.shape[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>self.outputs = <NUM_LIT:1><EOL><DEDENT><DEDENT>elif N == <NUM_LIT:3>:      <EOL><INDENT>self._zeros, self._poles, self._gain = args<EOL>self._update(N)<EOL>self.zeros = numpy.asarray(self.zeros)<EOL>self.poles = numpy.asarray(self.poles)<EOL>self.inputs = <NUM_LIT:1><EOL>if len(self.zeros.shape) > <NUM_LIT:1>:<EOL><INDENT>self.outputs = self.zeros.shape[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>self.outputs = <NUM_LIT:1><EOL><DEDENT><DEDENT>elif N == <NUM_LIT:4>:       <EOL><INDENT>self._A, self._B, self._C, self._D = abcd_normalize(*args)<EOL>self._update(N)<EOL>self.inputs = self.B.shape[-<NUM_LIT:1>]<EOL>self.outputs = self.C.shape[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Initialize the LTI system using either:

    - (numerator, denominator)
    - (zeros, poles, gain)
    - (A, B, C, D) : state-space.


return '<STR_LIT>'.format(<EOL>self.__class__.__name__,<EOL>repr(self.A),<EOL>repr(self.B),<EOL>repr(self.C),<EOL>repr(self.D),<EOL>)<EOL>

Canonical representation using state-space to preserve numerical
precision and any MIMO information


def impulse(self, X0=None, T=None, N=None):

return impulse(self, X0=X0, T=T, N=N)<EOL>

Return the impulse response of a continuous-time system.
See `scipy.signal.impulse` for details.


def step(self, X0=None, T=None, N=None):

return step(self, X0=X0, T=T, N=N)<EOL>

Return the step response of a continuous-time system.
See `scipy.signal.step` for details.


return lsim(self, U, T, X0=X0)<EOL>

Return the response of a continuous-time system to input `U`.
See `scipy.signal.lsim` for details.


def bode(self, w=None, n=<NUM_LIT:100>):

return bode(self, w=w, n=n)<EOL>

Calculate Bode magnitude and phase data of a continuous-time system.

Returns a 3-tuple containing arrays of frequencies [rad/s], magnitude
[dB] and phase [deg]. See `scipy.signal.bode` for details.

Notes
-----

.. versionadded:: 0.11.0

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

>>> s1 = signal.lti([1], [1, 1])
>>> w, mag, phase = s1.bode()

>>> plt.figure()
>>> plt.semilogx(w, mag)    # Bode magnitude plot
>>> plt.figure()
>>> plt.semilogx(w, phase)  # Bode phase plot
>>> plt.show()


def freqresp(self, w=None, n=<NUM_LIT>):

return freqresp(self, w=w, n=n)<EOL>

Calculate the frequency response of a continuous-time system.

Returns a 2-tuple containing arrays of frequencies [rad/s] and
complex magnitude.
See `scipy.signal.freqresp` for details.


if len(system) == <NUM_LIT:3>:<EOL><INDENT>a, b, c, d = tf2ss(system[<NUM_LIT:0>], system[<NUM_LIT:1>])<EOL>dt = system[<NUM_LIT:2>]<EOL><DEDENT>elif len(system) == <NUM_LIT:4>:<EOL><INDENT>a, b, c, d = zpk2ss(system[<NUM_LIT:0>], system[<NUM_LIT:1>], system[<NUM_LIT:2>])<EOL>dt = system[<NUM_LIT:3>]<EOL><DEDENT>elif len(system) == <NUM_LIT:5>:<EOL><INDENT>a, b, c, d, dt = system<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>if t is None:<EOL><INDENT>out_samples = max(u.shape)<EOL>stoptime = (out_samples - <NUM_LIT:1>) * dt<EOL><DEDENT>else:<EOL><INDENT>stoptime = t[-<NUM_LIT:1>]<EOL>out_samples = int(np.floor(stoptime / dt)) + <NUM_LIT:1><EOL><DEDENT>xout = np.zeros((out_samples, a.shape[<NUM_LIT:0>]))<EOL>yout = np.zeros((out_samples, c.shape[<NUM_LIT:0>]))<EOL>tout = np.linspace(<NUM_LIT:0.0>, stoptime, num=out_samples)<EOL>if x0 is None:<EOL><INDENT>xout[<NUM_LIT:0>,:] = np.zeros((a.shape[<NUM_LIT:1>],))<EOL><DEDENT>else:<EOL><INDENT>xout[<NUM_LIT:0>,:] = np.asarray(x0)<EOL><DEDENT>if t is None:<EOL><INDENT>u_dt = u<EOL><DEDENT>else:<EOL><INDENT>if len(u.shape) == <NUM_LIT:1>:<EOL><INDENT>u = u[:, np.newaxis]<EOL><DEDENT>u_dt_interp = interp1d(t, u.transpose(), copy=False, bounds_error=True)<EOL>u_dt = u_dt_interp(tout).transpose()<EOL><DEDENT>for i in range(<NUM_LIT:0>, out_samples - <NUM_LIT:1>):<EOL><INDENT>xout[i+<NUM_LIT:1>,:] = np.dot(a, xout[i,:]) + np.dot(b, u_dt[i,:])<EOL>yout[i,:] = np.dot(c, xout[i,:]) + np.dot(d, u_dt[i,:])<EOL><DEDENT>yout[out_samples-<NUM_LIT:1>,:] = np.dot(c, xout[out_samples-<NUM_LIT:1>,:]) +np.dot(d, u_dt[out_samples-<NUM_LIT:1>,:])<EOL>if len(system) == <NUM_LIT:5>:<EOL><INDENT>return tout, yout, xout<EOL><DEDENT>else:<EOL><INDENT>return tout, yout<EOL><DEDENT>

Simulate output of a discrete-time linear system.

Parameters
----------
system : class instance or tuple
    An instance of the LTI class, or a tuple describing the system.
    The following gives the number of elements in the tuple and
    the interpretation:

      - 3: (num, den, dt)
      - 4: (zeros, poles, gain, dt)
      - 5: (A, B, C, D, dt)

u : array_like
    An input array describing the input at each time `t` (interpolation is
    assumed between given times).  If there are multiple inputs, then each
    column of the rank-2 array represents an input.
t : array_like, optional
    The time steps at which the input is defined.  If `t` is given, the
    final value in `t` determines the number of steps returned in the
    output.
x0 : arry_like, optional
    The initial conditions on the state vector (zero by default).

Returns
-------
tout : ndarray
    Time values for the output, as a 1-D array.
yout : ndarray
    System response, as a 1-D array.
xout : ndarray, optional
    Time-evolution of the state-vector.  Only generated if the input is a
    state-space systems.

See Also
--------
lsim, dstep, dimpulse, cont2discrete

Examples
--------
A simple integrator transfer function with a discrete time step of 1.0
could be implemented as:

>>> from scipy import signal
>>> tf = ([1.0,], [1.0, -1.0], 1.0)
>>> t_in = [0.0, 1.0, 2.0, 3.0]
>>> u = np.asarray([0.0, 0.0, 1.0, 1.0])
>>> t_out, y = signal.dlsim(tf, u, t=t_in)
>>> y
array([ 0.,  0.,  0.,  1.])


def dimpulse(system, x0=None, t=None, n=None):

<EOL>if len(system) == <NUM_LIT:3>:<EOL><INDENT>n_inputs = <NUM_LIT:1><EOL>dt = system[<NUM_LIT:2>]<EOL><DEDENT>elif len(system) == <NUM_LIT:4>:<EOL><INDENT>n_inputs = <NUM_LIT:1><EOL>dt = system[<NUM_LIT:3>]<EOL><DEDENT>elif len(system) == <NUM_LIT:5>:<EOL><INDENT>n_inputs = system[<NUM_LIT:1>].shape[<NUM_LIT:1>]<EOL>dt = system[<NUM_LIT:4>]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>if n is None:<EOL><INDENT>n = <NUM_LIT:100><EOL><DEDENT>if t is None:<EOL><INDENT>t = np.linspace(<NUM_LIT:0>, n * dt, n, endpoint=False)<EOL><DEDENT>yout = None<EOL>for i in range(<NUM_LIT:0>, n_inputs):<EOL><INDENT>u = np.zeros((t.shape[<NUM_LIT:0>], n_inputs))<EOL>u[<NUM_LIT:0>,i] = <NUM_LIT:1.0><EOL>one_output = dlsim(system, u, t=t, x0=x0)<EOL>if yout is None:<EOL><INDENT>yout = (one_output[<NUM_LIT:1>],)<EOL><DEDENT>else:<EOL><INDENT>yout = yout + (one_output[<NUM_LIT:1>],)<EOL><DEDENT>tout = one_output[<NUM_LIT:0>]<EOL><DEDENT>return tout, yout<EOL>

Impulse response of discrete-time system.

    Parameters
    ----------
    system : tuple
        The following gives the number of elements in the tuple and
        the interpretation:

          * 3: (num, den, dt)
          * 4: (zeros, poles, gain, dt)
          * 5: (A, B, C, D, dt)

    x0 : array_like, optional
        Initial state-vector.  Defaults to zero.
    t : array_like, optional
        Time points.  Computed if not given.
    n : int, optional
        The number of time points to compute (if `t` is not given).

    Returns
    -------
    t : ndarray
        A 1-D array of time points.
    yout : tuple of array_like
        Impulse response of system.  Each element of the tuple represents
        the output of the system based on an impulse in each input.

    See Also
    --------
    impulse, dstep, dlsim, cont2discrete


def dstep(system, x0=None, t=None, n=None):

<EOL>if len(system) == <NUM_LIT:3>:<EOL><INDENT>n_inputs = <NUM_LIT:1><EOL>dt = system[<NUM_LIT:2>]<EOL><DEDENT>elif len(system) == <NUM_LIT:4>:<EOL><INDENT>n_inputs = <NUM_LIT:1><EOL>dt = system[<NUM_LIT:3>]<EOL><DEDENT>elif len(system) == <NUM_LIT:5>:<EOL><INDENT>n_inputs = system[<NUM_LIT:1>].shape[<NUM_LIT:1>]<EOL>dt = system[<NUM_LIT:4>]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>if n is None:<EOL><INDENT>n = <NUM_LIT:100><EOL><DEDENT>if t is None:<EOL><INDENT>t = np.linspace(<NUM_LIT:0>, n * dt, n, endpoint=False)<EOL><DEDENT>yout = None<EOL>for i in range(<NUM_LIT:0>, n_inputs):<EOL><INDENT>u = np.zeros((t.shape[<NUM_LIT:0>], n_inputs))<EOL>u[:,i] = np.ones((t.shape[<NUM_LIT:0>],))<EOL>one_output = dlsim(system, u, t=t, x0=x0)<EOL>if yout is None:<EOL><INDENT>yout = (one_output[<NUM_LIT:1>],)<EOL><DEDENT>else:<EOL><INDENT>yout = yout + (one_output[<NUM_LIT:1>],)<EOL><DEDENT>tout = one_output[<NUM_LIT:0>]<EOL><DEDENT>return tout, yout<EOL>

Step response of discrete-time system.

    Parameters
    ----------
    system : a tuple describing the system.
        The following gives the number of elements in the tuple and
        the interpretation:

          * 3: (num, den, dt)
          * 4: (zeros, poles, gain, dt)
          * 5: (A, B, C, D, dt)

    x0 : array_like, optional
        Initial state-vector (default is zero).
    t : array_like, optional
        Time points (computed if not given).
    n : int, optional
        Number of time points to compute if `t` is not given.

    Returns
    -------
    t : ndarray
        Output time points, as a 1-D array.
    yout : tuple of array_like
        Step response of system.  Each element of the tuple represents
        the output of the system based on a step response to each input.

    See Also
    --------
    step, dimpulse, dlsim, cont2discrete


def cont2discrete(sys, dt, method="<STR_LIT>", alpha=None):

if len(sys) == <NUM_LIT:2>:<EOL><INDENT>sysd = cont2discrete(tf2ss(sys[<NUM_LIT:0>], sys[<NUM_LIT:1>]), dt, method=method,<EOL>alpha=alpha)<EOL>return ss2tf(sysd[<NUM_LIT:0>], sysd[<NUM_LIT:1>], sysd[<NUM_LIT:2>], sysd[<NUM_LIT:3>]) + (dt,)<EOL><DEDENT>elif len(sys) == <NUM_LIT:3>:<EOL><INDENT>sysd = cont2discrete(zpk2ss(sys[<NUM_LIT:0>], sys[<NUM_LIT:1>], sys[<NUM_LIT:2>]), dt, method=method,<EOL>alpha=alpha)<EOL>return ss2zpk(sysd[<NUM_LIT:0>], sysd[<NUM_LIT:1>], sysd[<NUM_LIT:2>], sysd[<NUM_LIT:3>]) + (dt,)<EOL><DEDENT>elif len(sys) == <NUM_LIT:4>:<EOL><INDENT>a, b, c, d = sys<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>if alpha is None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>elif alpha < <NUM_LIT:0> or alpha > <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>ima = np.eye(a.shape[<NUM_LIT:0>]) - alpha*dt*a<EOL>ad = linalg.solve(ima, np.eye(a.shape[<NUM_LIT:0>]) + (<NUM_LIT:1.0>-alpha)*dt*a)<EOL>bd = linalg.solve(ima, dt*b)<EOL>cd = linalg.solve(ima.transpose(), c.transpose())<EOL>cd = cd.transpose()<EOL>dd = d + alpha*np.dot(c, bd)<EOL><DEDENT>elif method == '<STR_LIT>' or method == '<STR_LIT>':<EOL><INDENT>return cont2discrete(sys, dt, method="<STR_LIT>", alpha=<NUM_LIT:0.5>)<EOL><DEDENT>elif method == '<STR_LIT>' or method == '<STR_LIT>':<EOL><INDENT>return cont2discrete(sys, dt, method="<STR_LIT>", alpha=<NUM_LIT:0.0>)<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return cont2discrete(sys, dt, method="<STR_LIT>", alpha=<NUM_LIT:1.0>)<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>em_upper = np.hstack((a, b))<EOL>em_lower = np.hstack((np.zeros((b.shape[<NUM_LIT:1>], a.shape[<NUM_LIT:0>])),<EOL>np.zeros((b.shape[<NUM_LIT:1>], b.shape[<NUM_LIT:1>]))))<EOL>em = np.vstack((em_upper, em_lower))<EOL>ms = linalg.expm(dt * em)<EOL>ms = ms[:a.shape[<NUM_LIT:0>], :]<EOL>ad = ms[:, <NUM_LIT:0>:a.shape[<NUM_LIT:1>]]<EOL>bd = ms[:, a.shape[<NUM_LIT:1>]:]<EOL>cd = c<EOL>dd = d<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % method)<EOL><DEDENT>return ad, bd, cd, dd, dt<EOL>

Transform a continuous to a discrete state-space system.

Parameters
----------
sys : a tuple describing the system.
    The following gives the number of elements in the tuple and
    the interpretation:

       * 2: (num, den)
       * 3: (zeros, poles, gain)
       * 4: (A, B, C, D)

dt : float
    The discretization time step.
method : {"gbt", "bilinear", "euler", "backward_diff", "zoh"}
    Which method to use:

       * gbt: generalized bilinear transformation
       * bilinear: Tustin's approximation ("gbt" with alpha=0.5)
       * euler: Euler (or forward differencing) method ("gbt" with alpha=0)
       * backward_diff: Backwards differencing ("gbt" with alpha=1.0)
       * zoh: zero-order hold (default)

alpha : float within [0, 1]
    The generalized bilinear transformation weighting parameter, which
    should only be specified with method="gbt", and is ignored otherwise

Returns
-------
sysd : tuple containing the discrete system
    Based on the input type, the output will be of the form

    * (num, den, dt)   for transfer function input
    * (zeros, poles, gain, dt)   for zeros-poles-gain input
    * (A, B, C, D, dt) for state-space system input

Notes
-----
By default, the routine uses a Zero-Order Hold (zoh) method to perform
the transformation.  Alternatively, a generalized bilinear transformation
may be used, which includes the common Tustin's bilinear approximation,
an Euler's method technique, or a backwards differencing technique.

The Zero-Order Hold (zoh) method is based on [1]_, the generalized bilinear
approximation is based on [2]_ and [3]_.

References
----------
.. [1] http://en.wikipedia.org/wiki/Discretization#Discretization_of_linear_state_space_models

.. [2] http://techteach.no/publications/discretetime_signals_systems/discrete.pdf

.. [3] G. Zhang, X. Chen, and T. Chen, Digital redesign via the generalized
    bilinear transformation, Int. J. Control, vol. 82, no. 4, pp. 741-754,
    2009.
    (http://www.ece.ualberta.ca/~gfzhang/research/ZCC07_preprint.pdf)


def correlate(in1, in2, mode='<STR_LIT>'):

in1 = asarray(in1)<EOL>in2 = asarray(in2)<EOL>try:<EOL><INDENT>val = _modedict[mode]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if in1.ndim == in2.ndim == <NUM_LIT:0>:<EOL><INDENT>return in1 * in2<EOL><DEDENT>elif not in1.ndim == in2.ndim:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if mode == '<STR_LIT>':<EOL><INDENT>_check_valid_mode_shapes(in1.shape, in2.shape)<EOL>ps = [i - j + <NUM_LIT:1> for i, j in zip(in1.shape, in2.shape)]<EOL>out = np.empty(ps, in1.dtype)<EOL>z = sigtools._correlateND(in1, in2, out, val)<EOL><DEDENT>else:<EOL><INDENT>swapped_inputs = (mode == '<STR_LIT>') and (in2.size > in1.size)<EOL>if swapped_inputs:<EOL><INDENT>in1, in2 = in2, in1<EOL><DEDENT>ps = [i + j - <NUM_LIT:1> for i, j in zip(in1.shape, in2.shape)]<EOL>in1zpadded = np.zeros(ps, in1.dtype)<EOL>sc = [slice(<NUM_LIT:0>, i) for i in in1.shape]<EOL>in1zpadded[sc] = in1.copy()<EOL>if mode == '<STR_LIT>':<EOL><INDENT>out = np.empty(ps, in1.dtype)<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>out = np.empty(in1.shape, in1.dtype)<EOL><DEDENT>z = sigtools._correlateND(in1zpadded, in2, out, val)<EOL>if swapped_inputs:<EOL><INDENT>slice_obj = [slice(None, None, -<NUM_LIT:1>)] * len(z.shape)<EOL>z = z[slice_obj].conj()<EOL><DEDENT><DEDENT>return z<EOL>

Cross-correlate two N-dimensional arrays.

Cross-correlate `in1` and `in2`, with the output size determined by the
`mode` argument.

Parameters
----------
in1 : array_like
    First input.
in2 : array_like
    Second input. Should have the same number of dimensions as `in1`;
    if sizes of `in1` and `in2` are not equal then `in1` has to be the
    larger array.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear cross-correlation
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.

Returns
-------
correlate : array
    An N-dimensional array containing a subset of the discrete linear
    cross-correlation of `in1` with `in2`.

Notes
-----
The correlation z of two d-dimensional arrays x and y is defined as:

  z[...,k,...] = sum[..., i_l, ...]
                     x[..., i_l,...] * conj(y[..., i_l + k,...])

Examples
--------
Implement a matched filter using cross-correlation, to recover a signal
that has passed through a noisy channel.

>>> from scipy import signal
>>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128)
>>> sig_noise = sig + np.random.randn(len(sig))
>>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128

>>> import matplotlib.pyplot as plt
>>> clock = np.arange(64, len(sig), 128)
>>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True)
>>> ax_orig.plot(sig)
>>> ax_orig.plot(clock, sig[clock], 'ro')
>>> ax_orig.set_title('Original signal')
>>> ax_noise.plot(sig_noise)
>>> ax_noise.set_title('Signal with noise')
>>> ax_corr.plot(corr)
>>> ax_corr.plot(clock, corr[clock], 'ro')
>>> ax_corr.axhline(0.5, ls=':')
>>> ax_corr.set_title('Cross-correlated with rectangular pulse')
>>> ax_orig.margins(0, 0.1)
>>> fig.show()


if target <= <NUM_LIT:6>:<EOL><INDENT>return target<EOL><DEDENT>if not (target & (target-<NUM_LIT:1>)):<EOL><INDENT>return target<EOL><DEDENT>match = float('<STR_LIT>')  <EOL>p5 = <NUM_LIT:1><EOL>while p5 < target:<EOL><INDENT>p35 = p5<EOL>while p35 < target:<EOL><INDENT>quotient = -(-target // p35)<EOL>try:<EOL><INDENT>p2 = <NUM_LIT:2>**((quotient - <NUM_LIT:1>).bit_length())<EOL><DEDENT>except AttributeError:<EOL><INDENT>p2 = <NUM_LIT:2>**(len(bin(quotient - <NUM_LIT:1>)) - <NUM_LIT:2>)<EOL><DEDENT>N = p2 * p35<EOL>if N == target:<EOL><INDENT>return N<EOL><DEDENT>elif N < match:<EOL><INDENT>match = N<EOL><DEDENT>p35 *= <NUM_LIT:3><EOL>if p35 == target:<EOL><INDENT>return p35<EOL><DEDENT><DEDENT>if p35 < match:<EOL><INDENT>match = p35<EOL><DEDENT>p5 *= <NUM_LIT:5><EOL>if p5 == target:<EOL><INDENT>return p5<EOL><DEDENT><DEDENT>if p5 < match:<EOL><INDENT>match = p5<EOL><DEDENT>return match<EOL>

Find the next regular number greater than or equal to target.
Regular numbers are composites of the prime factors 2, 3, and 5.
Also known as 5-smooth numbers or Hamming numbers, these are the optimal
size for inputs to FFTPACK.

Target must be a positive integer.


def fftconvolve(in1, in2, mode="<STR_LIT>"):

in1 = asarray(in1)<EOL>in2 = asarray(in2)<EOL>if in1.ndim == in2.ndim == <NUM_LIT:0>:  <EOL><INDENT>return in1 * in2<EOL><DEDENT>elif not in1.ndim == in2.ndim:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif in1.size == <NUM_LIT:0> or in2.size == <NUM_LIT:0>:  <EOL><INDENT>return array([])<EOL><DEDENT>s1 = array(in1.shape)<EOL>s2 = array(in2.shape)<EOL>complex_result = (np.issubdtype(in1.dtype, np.complex) or<EOL>np.issubdtype(in2.dtype, np.complex))<EOL>shape = s1 + s2 - <NUM_LIT:1><EOL>if mode == "<STR_LIT>":<EOL><INDENT>_check_valid_mode_shapes(s1, s2)<EOL><DEDENT>fshape = [_next_regular(int(d)) for d in shape]<EOL>fslice = tuple([slice(<NUM_LIT:0>, int(sz)) for sz in shape])<EOL>if not complex_result and (_rfft_mt_safe or _rfft_lock.acquire(False)):<EOL><INDENT>try:<EOL><INDENT>ret = irfftn(rfftn(in1, fshape) *<EOL>rfftn(in2, fshape), fshape)[fslice].copy()<EOL><DEDENT>finally:<EOL><INDENT>if not _rfft_mt_safe:<EOL><INDENT>_rfft_lock.release()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>ret = ifftn(fftn(in1, fshape) * fftn(in2, fshape))[fslice].copy()<EOL>if not complex_result:<EOL><INDENT>ret = ret.real<EOL><DEDENT><DEDENT>if mode == "<STR_LIT>":<EOL><INDENT>return ret<EOL><DEDENT>elif mode == "<STR_LIT>":<EOL><INDENT>return _centered(ret, s1)<EOL><DEDENT>elif mode == "<STR_LIT>":<EOL><INDENT>return _centered(ret, s1 - s2 + <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>

Convolve two N-dimensional arrays using FFT.

    Convolve `in1` and `in2` using the fast Fourier transform method, with
    the output size determined by the `mode` argument.

    This is generally much faster than `convolve` for large arrays (n > ~500),
    but can be slower when only a few output values are needed, and can only
    output float arrays (int or object array inputs will be cast to float).

    Parameters
    ----------
    in1 : array_like
        First input.
    in2 : array_like
        Second input. Should have the same number of dimensions as `in1`;
        if sizes of `in1` and `in2` are not equal then `in1` has to be the
        larger array.
    mode : str {'full', 'valid', 'same'}, optional
        A string indicating the size of the output:

        ``full``
           The output is the full discrete linear convolution
           of the inputs. (Default)
        ``valid``
           The output consists only of those elements that do not
           rely on the zero-padding.
        ``same``
           The output is the same size as `in1`, centered
           with respect to the 'full' output.

    Returns
    -------
    out : array
        An N-dimensional array containing a subset of the discrete linear
        convolution of `in1` with `in2`.

    Examples
    --------
    Autocorrelation of white noise is an impulse.  (This is at least 100 times
    as fast as `convolve`.)

    >>> from scipy import signal
    >>> sig = np.random.randn(1000)
    >>> autocorr = signal.fftconvolve(sig, sig[::-1], mode='full')

    >>> import matplotlib.pyplot as plt
    >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1)
    >>> ax_orig.plot(sig)
    >>> ax_orig.set_title('White noise')
    >>> ax_mag.plot(np.arange(-len(sig)+1,len(sig)), autocorr)
    >>> ax_mag.set_title('Autocorrelation')
    >>> fig.show()

    Gaussian blur implemented using FFT convolution.  Notice the dark borders
    around the image, due to the zero-padding beyond its boundaries.
    The `convolve2d` function allows for other types of image boundaries,
    but is far slower.

    >>> from scipy import misc
    >>> lena = misc.lena()
    >>> kernel = np.outer(signal.gaussian(70, 8), signal.gaussian(70, 8))
    >>> blurred = signal.fftconvolve(lena, kernel, mode='same')

    >>> fig, (ax_orig, ax_kernel, ax_blurred) = plt.subplots(1, 3)
    >>> ax_orig.imshow(lena, cmap='gray')
    >>> ax_orig.set_title('Original')
    >>> ax_orig.set_axis_off()
    >>> ax_kernel.imshow(kernel, cmap='gray')
    >>> ax_kernel.set_title('Gaussian kernel')
    >>> ax_kernel.set_axis_off()
    >>> ax_blurred.imshow(blurred, cmap='gray')
    >>> ax_blurred.set_title('Blurred')
    >>> ax_blurred.set_axis_off()
    >>> fig.show()


def convolve(in1, in2, mode='<STR_LIT>'):

volume = asarray(in1)<EOL>kernel = asarray(in2)<EOL>if volume.ndim == kernel.ndim == <NUM_LIT:0>:<EOL><INDENT>return volume * kernel<EOL><DEDENT>slice_obj = [slice(None, None, -<NUM_LIT:1>)] * len(kernel.shape)<EOL>if np.iscomplexobj(kernel):<EOL><INDENT>return correlate(volume, kernel[slice_obj].conj(), mode)<EOL><DEDENT>else:<EOL><INDENT>return correlate(volume, kernel[slice_obj], mode)<EOL><DEDENT>

Convolve two N-dimensional arrays.

Convolve `in1` and `in2`, with the output size determined by the
`mode` argument.

Parameters
----------
in1 : array_like
    First input.
in2 : array_like
    Second input. Should have the same number of dimensions as `in1`;
    if sizes of `in1` and `in2` are not equal then `in1` has to be the
    larger array.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear convolution
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.

Returns
-------
convolve : array
    An N-dimensional array containing a subset of the discrete linear
    convolution of `in1` with `in2`.

See also
--------
numpy.polymul : performs polynomial multiplication (same operation, but
                also accepts poly1d objects)


domain = asarray(domain)<EOL>size = domain.shape<EOL>for k in range(len(size)):<EOL><INDENT>if (size[k] % <NUM_LIT:2>) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>return sigtools._order_filterND(a, domain, rank)<EOL>

Perform an order filter on an N-dimensional array.

Perform an order filter on the array in.  The domain argument acts as a
mask centered over each pixel.  The non-zero elements of domain are
used to select elements surrounding each input pixel which are placed
in a list.   The list is sorted, and the output for that pixel is the
element corresponding to rank in the sorted list.

Parameters
----------
a : ndarray
    The N-dimensional input array.
domain : array_like
    A mask array with the same number of dimensions as `in`.
    Each dimension should have an odd number of elements.
rank : int
    A non-negative integer which selects the element from the
    sorted list (0 corresponds to the smallest element, 1 is the
    next smallest element, etc.).

Returns
-------
out : ndarray
    The results of the order filter in an array with the same
    shape as `in`.

Examples
--------
>>> from scipy import signal
>>> x = np.arange(25).reshape(5, 5)
>>> domain = np.identity(3)
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
>>> signal.order_filter(x, domain, 0)
array([[  0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   1.,   2.,   0.],
       [  0.,   5.,   6.,   7.,   0.],
       [  0.,  10.,  11.,  12.,   0.],
       [  0.,   0.,   0.,   0.,   0.]])
>>> signal.order_filter(x, domain, 2)
array([[  6.,   7.,   8.,   9.,   4.],
       [ 11.,  12.,  13.,  14.,   9.],
       [ 16.,  17.,  18.,  19.,  14.],
       [ 21.,  22.,  23.,  24.,  19.],
       [ 20.,  21.,  22.,  23.,  24.]])


volume = atleast_1d(volume)<EOL>if kernel_size is None:<EOL><INDENT>kernel_size = [<NUM_LIT:3>] * len(volume.shape)<EOL><DEDENT>kernel_size = asarray(kernel_size)<EOL>if kernel_size.shape == ():<EOL><INDENT>kernel_size = np.repeat(kernel_size.item(), volume.ndim)<EOL><DEDENT>for k in range(len(volume.shape)):<EOL><INDENT>if (kernel_size[k] % <NUM_LIT:2>) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>domain = ones(kernel_size)<EOL>numels = product(kernel_size, axis=<NUM_LIT:0>)<EOL>order = numels // <NUM_LIT:2><EOL>return sigtools._order_filterND(volume, domain, order)<EOL>

Perform a median filter on an N-dimensional array.

Apply a median filter to the input array using a local window-size
given by `kernel_size`.

Parameters
----------
volume : array_like
    An N-dimensional input array.
kernel_size : array_like, optional
    A scalar or an N-length list giving the size of the median filter
    window in each dimension.  Elements of `kernel_size` should be odd.
    If `kernel_size` is a scalar, then this scalar is used as the size in
    each dimension. Default size is 3 for each dimension.

Returns
-------
out : ndarray
    An array the same size as input containing the median filtered
    result.


def wiener(im, mysize=None, noise=None):

im = asarray(im)<EOL>if mysize is None:<EOL><INDENT>mysize = [<NUM_LIT:3>] * len(im.shape)<EOL><DEDENT>mysize = asarray(mysize)<EOL>if mysize.shape == ():<EOL><INDENT>mysize = np.repeat(mysize.item(), im.ndim)<EOL><DEDENT>lMean = correlate(im, ones(mysize), '<STR_LIT>') / product(mysize, axis=<NUM_LIT:0>)<EOL>lVar = (correlate(im ** <NUM_LIT:2>, ones(mysize), '<STR_LIT>') / product(mysize, axis=<NUM_LIT:0>)<EOL>- lMean ** <NUM_LIT:2>)<EOL>if noise is None:<EOL><INDENT>noise = mean(ravel(lVar), axis=<NUM_LIT:0>)<EOL><DEDENT>res = (im - lMean)<EOL>res *= (<NUM_LIT:1> - noise / lVar)<EOL>res += lMean<EOL>out = where(lVar < noise, lMean, res)<EOL>return out<EOL>

Perform a Wiener filter on an N-dimensional array.

Apply a Wiener filter to the N-dimensional array `im`.

Parameters
----------
im : ndarray
    An N-dimensional array.
mysize : int or arraylike, optional
    A scalar or an N-length list giving the size of the Wiener filter
    window in each dimension.  Elements of mysize should be odd.
    If mysize is a scalar, then this scalar is used as the size
    in each dimension.
noise : float, optional
    The noise-power to use. If None, then noise is estimated as the
    average of the local variance of the input.

Returns
-------
out : ndarray
    Wiener filtered result with the same shape as `im`.


def convolve2d(in1, in2, mode='<STR_LIT>', boundary='<STR_LIT>', fillvalue=<NUM_LIT:0>):

in1 = asarray(in1)<EOL>in2 = asarray(in2)<EOL>if mode == '<STR_LIT>':<EOL><INDENT>_check_valid_mode_shapes(in1.shape, in2.shape)<EOL><DEDENT>val = _valfrommode(mode)<EOL>bval = _bvalfromboundary(boundary)<EOL>with warnings.catch_warnings():<EOL><INDENT>warnings.simplefilter('<STR_LIT:ignore>', np.ComplexWarning)<EOL>out = sigtools._convolve2d(in1, in2, <NUM_LIT:1>, val, bval, fillvalue)<EOL><DEDENT>return out<EOL>

Convolve two 2-dimensional arrays.

Convolve `in1` and `in2` with output size determined by `mode`, and
boundary conditions determined by `boundary` and `fillvalue`.

Parameters
----------
in1, in2 : array_like
    Two-dimensional input arrays to be convolved.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear convolution
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.

boundary : str {'fill', 'wrap', 'symm'}, optional
    A flag indicating how to handle boundaries:

    ``fill``
       pad input arrays with fillvalue. (default)
    ``wrap``
       circular boundary conditions.
    ``symm``
       symmetrical boundary conditions.

fillvalue : scalar, optional
    Value to fill pad input arrays with. Default is 0.

Returns
-------
out : ndarray
    A 2-dimensional array containing a subset of the discrete linear
    convolution of `in1` with `in2`.

Examples
--------
Compute the gradient of an image by 2D convolution with a complex Scharr
operator.  (Horizontal operator is real, vertical is imaginary.)  Use
symmetric boundary condition to avoid creating edges at the image
boundaries.

>>> from scipy import signal
>>> from scipy import misc
>>> lena = misc.lena()
>>> scharr = np.array([[ -3-3j, 0-10j,  +3 -3j],
...                    [-10+0j, 0+ 0j, +10 +0j],
...                    [ -3+3j, 0+10j,  +3 +3j]]) # Gx + j*Gy
>>> grad = signal.convolve2d(lena, scharr, boundary='symm', mode='same')

>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(1, 3)
>>> ax_orig.imshow(lena, cmap='gray')
>>> ax_orig.set_title('Original')
>>> ax_orig.set_axis_off()
>>> ax_mag.imshow(np.absolute(grad), cmap='gray')
>>> ax_mag.set_title('Gradient magnitude')
>>> ax_mag.set_axis_off()
>>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles
>>> ax_ang.set_title('Gradient orientation')
>>> ax_ang.set_axis_off()
>>> fig.show()


def correlate2d(in1, in2, mode='<STR_LIT>', boundary='<STR_LIT>', fillvalue=<NUM_LIT:0>):

in1 = asarray(in1)<EOL>in2 = asarray(in2)<EOL>if mode == '<STR_LIT>':<EOL><INDENT>_check_valid_mode_shapes(in1.shape, in2.shape)<EOL><DEDENT>val = _valfrommode(mode)<EOL>bval = _bvalfromboundary(boundary)<EOL>with warnings.catch_warnings():<EOL><INDENT>warnings.simplefilter('<STR_LIT:ignore>', np.ComplexWarning)<EOL>out = sigtools._convolve2d(in1, in2, <NUM_LIT:0>, val, bval, fillvalue)<EOL><DEDENT>return out<EOL>

Cross-correlate two 2-dimensional arrays.

Cross correlate `in1` and `in2` with output size determined by `mode`, and
boundary conditions determined by `boundary` and `fillvalue`.

Parameters
----------
in1, in2 : array_like
    Two-dimensional input arrays to be convolved.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear cross-correlation
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.

boundary : str {'fill', 'wrap', 'symm'}, optional
    A flag indicating how to handle boundaries:

    ``fill``
       pad input arrays with fillvalue. (default)
    ``wrap``
       circular boundary conditions.
    ``symm``
       symmetrical boundary conditions.

fillvalue : scalar, optional
    Value to fill pad input arrays with. Default is 0.

Returns
-------
correlate2d : ndarray
    A 2-dimensional array containing a subset of the discrete linear
    cross-correlation of `in1` with `in2`.

Examples
--------
Use 2D cross-correlation to find the location of a template in a noisy
image:

>>> from scipy import signal
>>> from scipy import misc
>>> lena = misc.lena() - misc.lena().mean()
>>> template = np.copy(lena[235:295, 310:370]) # right eye
>>> template -= template.mean()
>>> lena = lena + np.random.randn(*lena.shape) * 50 # add noise
>>> corr = signal.correlate2d(lena, template, boundary='symm', mode='same')
>>> y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match

>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(1, 3)
>>> ax_orig.imshow(lena, cmap='gray')
>>> ax_orig.set_title('Original')
>>> ax_orig.set_axis_off()
>>> ax_template.imshow(template, cmap='gray')
>>> ax_template.set_title('Template')
>>> ax_template.set_axis_off()
>>> ax_corr.imshow(corr, cmap='gray')
>>> ax_corr.set_title('Cross-correlation')
>>> ax_corr.set_axis_off()
>>> ax_orig.plot(x, y, 'ro')
>>> fig.show()