grouped_results = defaultdict(list)<EOL>for res in self.results:<EOL><INDENT>grouped_results[res.name].append(res)<EOL><DEDENT>averaged_results = dict()<EOL>for name, result_list in grouped_results.items():<EOL><INDENT>newres = OptimizeResult()<EOL>newres.name = name<EOL>newres.mean_nfev = np.mean([r.nfev for r in result_list])<EOL>newres.mean_njev = np.mean([r.njev for r in result_list])<EOL>newres.mean_nhev = np.mean([r.nhev for r in result_list])<EOL>newres.mean_time = np.mean([r.time for r in result_list])<EOL>newres.ntrials = len(result_list)<EOL>newres.nfail = len([r for r in result_list if not r.success])<EOL>try:<EOL><INDENT>newres.ndim = len(result_list[<NUM_LIT:0>].x)<EOL><DEDENT>except TypeError:<EOL><INDENT>newres.ndim = <NUM_LIT:1><EOL><DEDENT>averaged_results[name] = newres<EOL><DEDENT>return averaged_results.values()<EOL>

group the results by minimizer and average over the runs


if x < <NUM_LIT:0>:<EOL><INDENT>return -<NUM_LIT:1.><EOL><DEDENT>elif x > <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:1.><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0.><EOL><DEDENT>


def scalar_search_wolfe2(phi, derphi=None, phi0=None,<EOL>old_phi0=None, derphi0=None,<EOL>c1=<NUM_LIT>, c2=<NUM_LIT>, amax=<NUM_LIT:50>):

if phi0 is None:<EOL><INDENT>phi0 = phi(<NUM_LIT:0.>)<EOL><DEDENT>if derphi0 is None and derphi is not None:<EOL><INDENT>derphi0 = derphi(<NUM_LIT:0.>)<EOL><DEDENT>alpha0 = <NUM_LIT:0><EOL>if old_phi0 is not None and derphi0 != <NUM_LIT:0>:<EOL><INDENT>alpha1 = min(<NUM_LIT:1.0>, <NUM_LIT>*<NUM_LIT:2>*(phi0 - old_phi0)/derphi0)<EOL><DEDENT>else:<EOL><INDENT>alpha1 = <NUM_LIT:1.0><EOL><DEDENT>if alpha1 < <NUM_LIT:0>:<EOL><INDENT>alpha1 = <NUM_LIT:1.0><EOL><DEDENT>if alpha1 == <NUM_LIT:0>:<EOL><INDENT>alpha_star = None<EOL>phi_star = phi0<EOL>phi0 = old_phi0<EOL>derphi_star = None<EOL><DEDENT>phi_a1 = phi(alpha1)<EOL>phi_a0 = phi0<EOL>derphi_a0 = derphi0<EOL>i = <NUM_LIT:1><EOL>maxiter = <NUM_LIT:10><EOL>for i in xrange(maxiter):<EOL><INDENT>if alpha1 == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>if (phi_a1 > phi0 + c1 * alpha1 * derphi0) or((phi_a1 >= phi_a0) and (i > <NUM_LIT:1>)):<EOL><INDENT>alpha_star, phi_star, derphi_star =_zoom(alpha0, alpha1, phi_a0,<EOL>phi_a1, derphi_a0, phi, derphi,<EOL>phi0, derphi0, c1, c2)<EOL>break<EOL><DEDENT>derphi_a1 = derphi(alpha1)<EOL>if (abs(derphi_a1) <= -c2*derphi0):<EOL><INDENT>alpha_star = alpha1<EOL>phi_star = phi_a1<EOL>derphi_star = derphi_a1<EOL>break<EOL><DEDENT>if (derphi_a1 >= <NUM_LIT:0>):<EOL><INDENT>alpha_star, phi_star, derphi_star =_zoom(alpha1, alpha0, phi_a1,<EOL>phi_a0, derphi_a1, phi, derphi,<EOL>phi0, derphi0, c1, c2)<EOL>break<EOL><DEDENT>alpha2 = <NUM_LIT:2> * alpha1   <EOL>i = i + <NUM_LIT:1><EOL>alpha0 = alpha1<EOL>alpha1 = alpha2<EOL>phi_a0 = phi_a1<EOL>phi_a1 = phi(alpha1)<EOL>derphi_a0 = derphi_a1<EOL><DEDENT>else:<EOL><INDENT>alpha_star = alpha1<EOL>phi_star = phi_a1<EOL>derphi_star = None<EOL><DEDENT>return alpha_star, phi_star, phi0, derphi_star<EOL>

Find alpha that satisfies strong Wolfe conditions.

    alpha > 0 is assumed to be a descent direction.

    Parameters
    ----------
    phi : callable f(x,*args)
        Objective scalar function.

    derphi : callable f'(x,*args), optional
        Objective function derivative (can be None)
    phi0 : float, optional
        Value of phi at s=0
    old_phi0 : float, optional
        Value of phi at previous point
    derphi0 : float, optional
        Value of derphi at s=0
    args : tuple
        Additional arguments passed to objective function.
    c1 : float
        Parameter for Armijo condition rule.
    c2 : float
        Parameter for curvature condition rule.

    Returns
    -------
    alpha_star : float
        Best alpha
    phi_star
        phi at alpha_star
    phi0
        phi at 0
    derphi_star
        derphi at alpha_star

    Notes
    -----
    Uses the line search algorithm to enforce strong Wolfe
    conditions.  See Wright and Nocedal, 'Numerical Optimization',
    1999, pg. 59-60.

    For the zoom phase it uses an algorithm by [...].


assert(self.dims is not None)<EOL>lrange = self.lower<EOL>urange = self.upper<EOL>fmax = _double_min<EOL>fmin = _double_max<EOL>for _ in range(self.Ninit):<EOL><INDENT>x0 = random.uniform(size=self.dims)*(urange-lrange) + lrange<EOL>fval = self.func(x0, *self.args)<EOL>self.feval += <NUM_LIT:1><EOL>if fval > fmax:<EOL><INDENT>fmax = fval<EOL><DEDENT>if fval < fmin:<EOL><INDENT>fmin = fval<EOL>best_state.cost = fval<EOL>best_state.x = array(x0)<EOL><DEDENT><DEDENT>self.T0 = (fmax-fmin)*<NUM_LIT><EOL>return best_state.x<EOL>

Find a matching starting temperature and starting parameters vector
        i.e. find x0 such that func(x0) = T0.

        Parameters
        ----------
        best_state : _state
            A _state object to store the function value and x0 found.

        Returns
        -------
        x0 : array
            The starting parameters vector.


def _solve_simplex(T, n, basis, maxiter=<NUM_LIT:1000>, phase=<NUM_LIT:2>, callback=None,<EOL>tol=<NUM_LIT>, nit0=<NUM_LIT:0>, bland=False):

nit = nit0<EOL>complete = False<EOL>solution = np.zeros(T.shape[<NUM_LIT:1>]-<NUM_LIT:1>, dtype=np.float64)<EOL>if phase == <NUM_LIT:1>:<EOL><INDENT>m = T.shape[<NUM_LIT:0>]-<NUM_LIT:2><EOL><DEDENT>elif phase == <NUM_LIT:2>:<EOL><INDENT>m = T.shape[<NUM_LIT:0>]-<NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>while not complete:<EOL><INDENT>pivcol_found, pivcol = _pivot_col(T, tol, bland)<EOL>if not pivcol_found:<EOL><INDENT>pivcol = np.nan<EOL>pivrow = np.nan<EOL>status = <NUM_LIT:0><EOL>complete = True<EOL><DEDENT>else:<EOL><INDENT>pivrow_found, pivrow = _pivot_row(T, pivcol, phase, tol)<EOL>if not pivrow_found:<EOL><INDENT>status = <NUM_LIT:3><EOL>complete = True<EOL><DEDENT><DEDENT>if callback is not None:<EOL><INDENT>solution[:] = <NUM_LIT:0><EOL>solution[basis[:m]] = T[:m, -<NUM_LIT:1>]<EOL>callback(solution[:n], **{"<STR_LIT>": T,<EOL>"<STR_LIT>":phase,<EOL>"<STR_LIT>":nit,<EOL>"<STR_LIT>":(pivrow, pivcol),<EOL>"<STR_LIT>":basis,<EOL>"<STR_LIT>": complete and phase == <NUM_LIT:2>})<EOL><DEDENT>if not complete:<EOL><INDENT>if nit >= maxiter:<EOL><INDENT>status = <NUM_LIT:1><EOL>complete = True<EOL><DEDENT>else:<EOL><INDENT>basis[pivrow] = pivcol<EOL>pivval = T[pivrow][pivcol]<EOL>T[pivrow, :] = T[pivrow, :] / pivval<EOL>for irow in range(T.shape[<NUM_LIT:0>]):<EOL><INDENT>if irow != pivrow:<EOL><INDENT>T[irow, :] = T[irow, :] - T[pivrow, :]*T[irow, pivcol]<EOL><DEDENT><DEDENT>nit += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return nit, status<EOL>

Solve a linear programming problem in "standard maximization form" using
the Simplex Method.

Minimize :math:`f = c^T x`

subject to

.. math::

    Ax = b
    x_i >= 0
    b_j >= 0

Parameters
----------
T : array_like
    A 2-D array representing the simplex T corresponding to the
    maximization problem.  It should have the form:

    [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
     [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
     .
     .
     .
     [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
     [c[0],   c[1], ...,   c[n_total],    0]]

    for a Phase 2 problem, or the form:

    [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
     [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
     .
     .
     .
     [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
     [c[0],   c[1], ...,   c[n_total],   0],
     [c'[0],  c'[1], ...,  c'[n_total],  0]]

     for a Phase 1 problem (a Problem in which a basic feasible solution is
     sought prior to maximizing the actual objective.  T is modified in
     place by _solve_simplex.
n : int
    The number of true variables in the problem.
basis : array
    An array of the indices of the basic variables, such that basis[i]
    contains the column corresponding to the basic variable for row i.
    Basis is modified in place by _solve_simplex
maxiter : int
    The maximum number of iterations to perform before aborting the
    optimization.
phase : int
    The phase of the optimization being executed.  In phase 1 a basic
    feasible solution is sought and the T has an additional row representing
    an alternate objective function.
callback : callable
    If a callback function is provided, it will be called within each
    iteration of the simplex algorithm. The callback must have the
    signature `callback(xk, **kwargs)` where xk is the current solution
    vector and kwargs is a dictionary containing the following::
    "T" : The current Simplex algorithm T
    "nit" : The current iteration.
    "pivot" : The pivot (row, column) used for the next iteration.
    "phase" : Whether the algorithm is in Phase 1 or Phase 2.
    "basis" : The indices of the columns of the basic variables.
tol : float
    The tolerance which determines when a solution is "close enough" to
    zero in Phase 1 to be considered a basic feasible solution or close
    enough to positive to to serve as an optimal solution.
nit0 : int
    The initial iteration number used to keep an accurate iteration total
    in a two-phase problem.
bland : bool
    If True, choose pivots using Bland's rule [3].  In problems which
    fail to converge due to cycling, using Bland's rule can provide
    convergence at the expense of a less optimal path about the simplex.

Returns
-------
res : OptimizeResult
    The optimization result represented as a ``OptimizeResult`` object.
    Important attributes are: ``x`` the solution array, ``success`` a
    Boolean flag indicating if the optimizer exited successfully and
    ``message`` which describes the cause of the termination. Possible
    values for the ``status`` attribute are:
     0 : Optimization terminated successfully
     1 : Iteration limit reached
     2 : Problem appears to be infeasible
     3 : Problem appears to be unbounded

    See `OptimizeResult` for a description of other attributes.


def _pivot_col(T, tol=<NUM_LIT>, bland=False):

ma = np.ma.masked_where(T[-<NUM_LIT:1>, :-<NUM_LIT:1>] >= -tol, T[-<NUM_LIT:1>, :-<NUM_LIT:1>], copy=False)<EOL>if ma.count() == <NUM_LIT:0>:<EOL><INDENT>return False, np.nan<EOL><DEDENT>if bland:<EOL><INDENT>return True, np.where(ma.mask == False)[<NUM_LIT:0>][<NUM_LIT:0>]<EOL><DEDENT>return True, np.ma.where(ma == ma.min())[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>

Given a linear programming simplex tableau, determine the column
of the variable to enter the basis.

Parameters
----------
T : 2D ndarray
    The simplex tableau.
tol : float
    Elements in the objective row larger than -tol will not be considered
    for pivoting.  Nominally this value is zero, but numerical issues
    cause a tolerance about zero to be necessary.
bland : bool
    If True, use Bland's rule for selection of the column (select the
    first column with a negative coefficient in the objective row,
    regardless of magnitude).

Returns
-------
status: bool
    True if a suitable pivot column was found, otherwise False.
    A return of False indicates that the linear programming simplex
    algorithm is complete.
col: int
    The index of the column of the pivot element.
    If status is False, col will be returned as nan.


def _linprog_simplex(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,<EOL>bounds=None, maxiter=<NUM_LIT:1000>, disp=False, callback=None,<EOL>tol=<NUM_LIT>, bland=False, **unknown_options):

_check_unknown_options(unknown_options)<EOL>status = <NUM_LIT:0><EOL>messages = {<NUM_LIT:0>: "<STR_LIT>",<EOL><NUM_LIT:1>: "<STR_LIT>",<EOL><NUM_LIT:2>: "<STR_LIT>"<EOL>"<STR_LIT>",<EOL><NUM_LIT:3>: "<STR_LIT>",<EOL><NUM_LIT:4>: "<STR_LIT>"}<EOL>have_floor_variable = False<EOL>cc = np.asarray(c)<EOL>f0 = <NUM_LIT:0><EOL>n = len(c)<EOL>Aeq = np.asarray(A_eq) if A_eq is not None else np.empty([<NUM_LIT:0>, len(cc)])<EOL>Aub = np.asarray(A_ub) if A_ub is not None else np.empty([<NUM_LIT:0>, len(cc)])<EOL>beq = np.ravel(np.asarray(b_eq)) if b_eq is not None else np.empty([<NUM_LIT:0>])<EOL>bub = np.ravel(np.asarray(b_ub)) if b_ub is not None else np.empty([<NUM_LIT:0>])<EOL>L = np.zeros(n, dtype=np.float64)<EOL>U = np.ones(n, dtype=np.float64)*np.inf<EOL>if bounds is None or len(bounds) == <NUM_LIT:0>:<EOL><INDENT>pass<EOL><DEDENT>elif len(bounds) == <NUM_LIT:2> and not hasattr(bounds[<NUM_LIT:0>], '<STR_LIT>'):<EOL><INDENT>L = np.asarray(n*[bounds[<NUM_LIT:0>]], dtype=np.float64)<EOL>U = np.asarray(n*[bounds[<NUM_LIT:1>]], dtype=np.float64)<EOL><DEDENT>else:<EOL><INDENT>if len(bounds) != n:<EOL><INDENT>status = -<NUM_LIT:1><EOL>message = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>for i in range(n):<EOL><INDENT>if len(bounds[i]) != <NUM_LIT:2>:<EOL><INDENT>raise IndexError()<EOL><DEDENT>L[i] = bounds[i][<NUM_LIT:0>] if bounds[i][<NUM_LIT:0>] is not None else -np.inf<EOL>U[i] = bounds[i][<NUM_LIT:1>] if bounds[i][<NUM_LIT:1>] is not None else np.inf<EOL><DEDENT><DEDENT>except IndexError:<EOL><INDENT>status = -<NUM_LIT:1><EOL>message = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>if np.any(L == -np.inf):<EOL><INDENT>n = n + <NUM_LIT:1><EOL>L = np.concatenate([np.array([<NUM_LIT:0>]), L])<EOL>U = np.concatenate([np.array([np.inf]), U])<EOL>cc = np.concatenate([np.array([<NUM_LIT:0>]), cc])<EOL>Aeq = np.hstack([np.zeros([Aeq.shape[<NUM_LIT:0>], <NUM_LIT:1>]), Aeq])<EOL>Aub = np.hstack([np.zeros([Aub.shape[<NUM_LIT:0>], <NUM_LIT:1>]), Aub])<EOL>have_floor_variable = True<EOL><DEDENT>for i in range(n):<EOL><INDENT>if(L[i] > U[i]):<EOL><INDENT>status = -<NUM_LIT:1><EOL>message = ("<STR_LIT>"<EOL>"<STR_LIT>" % (i, i))<EOL><DEDENT>if np.isinf(L[i]) and L[i] > <NUM_LIT:0>:<EOL><INDENT>status = -<NUM_LIT:1><EOL>message = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if np.isinf(U[i]) and U[i] < <NUM_LIT:0>:<EOL><INDENT>status = -<NUM_LIT:1><EOL>message = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if np.isfinite(L[i]) and L[i] > <NUM_LIT:0>:<EOL><INDENT>Aub = np.vstack([Aub, np.zeros(n)])<EOL>Aub[-<NUM_LIT:1>, i] = -<NUM_LIT:1><EOL>bub = np.concatenate([bub, np.array([-L[i]])])<EOL>L[i] = <NUM_LIT:0><EOL><DEDENT>if np.isfinite(U[i]):<EOL><INDENT>Aub = np.vstack([Aub, np.zeros(n)])<EOL>Aub[-<NUM_LIT:1>, i] = <NUM_LIT:1><EOL>bub = np.concatenate([bub, np.array([U[i]])])<EOL>U[i] = np.inf<EOL><DEDENT><DEDENT>for i in range(<NUM_LIT:0>, n):<EOL><INDENT>if L[i] < <NUM_LIT:0>:<EOL><INDENT>if np.isfinite(L[i]) and L[i] < <NUM_LIT:0>:<EOL><INDENT>beq[:] = beq[:] - Aeq[:, i] * L[i]<EOL>bub[:] = bub[:] - Aub[:, i] * L[i]<EOL>f0 = f0 - cc[i] * L[i]<EOL><DEDENT>else:<EOL><INDENT>Aeq[:, <NUM_LIT:0>] = Aeq[:, <NUM_LIT:0>] - Aeq[:, i]<EOL>Aub[:, <NUM_LIT:0>] = Aub[:, <NUM_LIT:0>] - Aub[:, i]<EOL>cc[<NUM_LIT:0>] = cc[<NUM_LIT:0>] - cc[i]<EOL><DEDENT><DEDENT>if np.isinf(U[i]):<EOL><INDENT>if U[i] < <NUM_LIT:0>:<EOL><INDENT>status = -<NUM_LIT:1><EOL>message = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>mub = len(bub)<EOL>meq = len(beq)<EOL>m = mub+meq<EOL>n_slack = mub<EOL>n_artificial = meq + _count_nonzero(bub < <NUM_LIT:0>)<EOL>try:<EOL><INDENT>Aub_rows, Aub_cols = Aub.shape<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>Aeq_rows, Aeq_cols = Aeq.shape<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if Aeq_rows != meq:<EOL><INDENT>status = -<NUM_LIT:1><EOL>message = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if Aub_rows != mub:<EOL><INDENT>status = -<NUM_LIT:1><EOL>message = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if Aeq_cols > <NUM_LIT:0> and Aeq_cols != n:<EOL><INDENT>status = -<NUM_LIT:1><EOL>message = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if Aub_cols > <NUM_LIT:0> and Aub_cols != n:<EOL><INDENT>status = -<NUM_LIT:1><EOL>message = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if status != <NUM_LIT:0>:<EOL><INDENT>raise ValueError(message)<EOL><DEDENT>T = np.zeros([m+<NUM_LIT:2>, n+n_slack+n_artificial+<NUM_LIT:1>])<EOL>T[-<NUM_LIT:2>, :n] = cc<EOL>T[-<NUM_LIT:2>, -<NUM_LIT:1>] = f0<EOL>b = T[:-<NUM_LIT:2>, -<NUM_LIT:1>]<EOL>if meq > <NUM_LIT:0>:<EOL><INDENT>T[:meq, :n] = Aeq<EOL>b[:meq] = beq<EOL><DEDENT>if mub > <NUM_LIT:0>:<EOL><INDENT>T[meq:meq+mub, :n] = Aub<EOL>b[meq:meq+mub] = bub<EOL>np.fill_diagonal(T[meq:m, n:n+n_slack], <NUM_LIT:1>)<EOL><DEDENT>slcount = <NUM_LIT:0><EOL>avcount = <NUM_LIT:0><EOL>basis = np.zeros(m, dtype=int)<EOL>r_artificial = np.zeros(n_artificial, dtype=int)<EOL>for i in range(m):<EOL><INDENT>if i < meq or b[i] < <NUM_LIT:0>:<EOL><INDENT>basis[i] = n+n_slack+avcount<EOL>r_artificial[avcount] = i<EOL>avcount += <NUM_LIT:1><EOL>if b[i] < <NUM_LIT:0>:<EOL><INDENT>b[i] *= -<NUM_LIT:1><EOL>T[i, :-<NUM_LIT:1>] *= -<NUM_LIT:1><EOL><DEDENT>T[i, basis[i]] = <NUM_LIT:1><EOL>T[-<NUM_LIT:1>, basis[i]] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>basis[i] = n+slcount<EOL>slcount += <NUM_LIT:1><EOL><DEDENT><DEDENT>for r in r_artificial:<EOL><INDENT>T[-<NUM_LIT:1>, :] = T[-<NUM_LIT:1>, :] - T[r, :]<EOL><DEDENT>nit1, status = _solve_simplex(T, n, basis, phase=<NUM_LIT:1>, callback=callback,<EOL>maxiter=maxiter, tol=tol, bland=bland)<EOL>if abs(T[-<NUM_LIT:1>, -<NUM_LIT:1>]) < tol:<EOL><INDENT>T = T[:-<NUM_LIT:1>, :]<EOL>T = np.delete(T, np.s_[n+n_slack:n+n_slack+n_artificial], <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>status = <NUM_LIT:2><EOL><DEDENT>if status != <NUM_LIT:0>:<EOL><INDENT>message = messages[status]<EOL>if disp:<EOL><INDENT>print(message)<EOL><DEDENT>return OptimizeResult(x=np.nan, fun=-T[-<NUM_LIT:1>, -<NUM_LIT:1>], nit=nit1, status=status,<EOL>message=message, success=False)<EOL><DEDENT>nit2, status = _solve_simplex(T, n, basis, maxiter=maxiter-nit1, phase=<NUM_LIT:2>,<EOL>callback=callback, tol=tol, nit0=nit1,<EOL>bland=bland)<EOL>solution = np.zeros(n+n_slack+n_artificial)<EOL>solution[basis[:m]] = T[:m, -<NUM_LIT:1>]<EOL>x = solution[:n]<EOL>slack = solution[n:n+n_slack]<EOL>masked_L = np.ma.array(L, mask=np.isinf(L), fill_value=<NUM_LIT:0.0>).filled()<EOL>x = x + masked_L<EOL>if have_floor_variable:<EOL><INDENT>for i in range(<NUM_LIT:1>, n):<EOL><INDENT>if np.isinf(L[i]):<EOL><INDENT>x[i] -= x[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>x = x[<NUM_LIT:1>:]<EOL><DEDENT>obj = -T[-<NUM_LIT:1>, -<NUM_LIT:1>]<EOL>if status in (<NUM_LIT:0>, <NUM_LIT:1>):<EOL><INDENT>if disp:<EOL><INDENT>print(messages[status])<EOL>print("<STR_LIT>".format(obj))<EOL>print("<STR_LIT>".format(nit2))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if disp:<EOL><INDENT>print(messages[status])<EOL>print("<STR_LIT>".format(nit2))<EOL><DEDENT><DEDENT>return OptimizeResult(x=x, fun=obj, nit=int(nit2), status=status, slack=slack,<EOL>message=messages[status], success=(status == <NUM_LIT:0>))<EOL>

Solve the following linear programming problem via a two-phase
simplex algorithm.

maximize:     c^T * x

subject to:   A_ub * x <= b_ub
              A_eq * x == b_eq

Parameters
----------
c : array_like
    Coefficients of the linear objective function to be maximized.
A_ub :
    2-D array which, when matrix-multiplied by x, gives the values of the
    upper-bound inequality constraints at x.
b_ub : array_like
    1-D array of values representing the upper-bound of each inequality
    constraint (row) in A_ub.
A_eq : array_like
    2-D array which, when matrix-multiplied by x, gives the values of the
    equality constraints at x.
b_eq : array_like
    1-D array of values representing the RHS of each equality constraint
    (row) in A_eq.
bounds : array_like
    The bounds for each independent variable in the solution, which can take
    one of three forms::
    None : The default bounds, all variables are non-negative.
    (lb, ub) : If a 2-element sequence is provided, the same
              lower bound (lb) and upper bound (ub) will be applied
              to all variables.
    [(lb_0, ub_0), (lb_1, ub_1), ...] : If an n x 2 sequence is provided,
              each variable x_i will be bounded by lb[i] and ub[i].
    Infinite bounds are specified using -np.inf (negative)
    or np.inf (positive).
maxiter : int
   The maximum number of iterations to perform.
disp : bool
    If True, print exit status message to sys.stdout
callback : callable
    If a callback function is provide, it will be called within each
    iteration of the simplex algorithm. The callback must have the
    signature `callback(xk, **kwargs)` where xk is the current solution
    vector and kwargs is a dictionary containing the following::
    "tableau" : The current Simplex algorithm tableau
    "nit" : The current iteration.
    "pivot" : The pivot (row, column) used for the next iteration.
    "phase" : Whether the algorithm is in Phase 1 or Phase 2.
    "bv" : A structured array containing a string representation of each
           basic variable and its current value.
tol : float
    The tolerance which determines when a solution is "close enough" to zero
    in Phase 1 to be considered a basic feasible solution or close enough
    to positive to to serve as an optimal solution.
bland : bool
    If True, use Bland's anti-cycling rule [3] to choose pivots to
    prevent cycling.  If False, choose pivots which should lead to a
    converged solution more quickly.  The latter method is subject to
    cycling (non-convergence) in rare instances.

Returns
-------
A scipy.optimize.OptimizeResult consisting of the following fields::
    x : ndarray
        The independent variable vector which optimizes the linear
        programming problem.
    slack : ndarray
        The values of the slack variables.  Each slack variable corresponds
        to an inequality constraint.  If the slack is zero, then the
        corresponding constraint is active.
    success : bool
        Returns True if the algorithm succeeded in finding an optimal
        solution.
    status : int
        An integer representing the exit status of the optimization::
         0 : Optimization terminated successfully
         1 : Iteration limit reached
         2 : Problem appears to be infeasible
         3 : Problem appears to be unbounded
    nit : int
        The number of iterations performed.
    message : str
        A string descriptor of the exit status of the optimization.

Examples
--------
Consider the following problem:

Minimize: f = -1*x[0] + 4*x[1]

Subject to: -3*x[0] + 1*x[1] <= 6
             1*x[0] + 2*x[1] <= 4
                        x[1] >= -3

where:  -inf <= x[0] <= inf

This problem deviates from the standard linear programming problem.  In
standard form, linear programming problems assume the variables x are
non-negative.  Since the variables don't have standard bounds where
0 <= x <= inf, the bounds of the variables must be explicitly set.

There are two upper-bound constraints, which can be expressed as

dot(A_ub, x) <= b_ub

The input for this problem is as follows:

>>> c = [-1, 4]
>>> A = [[-3, 1], [1, 2]]
>>> b = [6, 4]
>>> x0_bnds = (None, None)
>>> x1_bnds = (-3, None)
>>> res = linprog(c, A, b, bounds=(x0_bnds, x1_bnds), options={"disp":True})
>>> print(res)
Optimization terminated successfully.
     Current function value: 11.428571
     Iterations: 2
status: 0
success: True
fun: 11.428571428571429
x: array([-1.14285714,  2.57142857])
slack: array([], dtype=np.float64)
message: 'Optimization terminated successfully.'
nit: 2

References
----------
.. [1] Dantzig, George B., Linear programming and extensions. Rand
       Corporation Research Study Princeton Univ. Press, Princeton, NJ, 1963
.. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
       Mathematical Programming", McGraw-Hill, Chapter 4.
.. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
       Mathematics of Operations Research (2), 1977: pp. 103-107.


nit = kwargs["<STR_LIT>"]<EOL>if nit == <NUM_LIT:0>:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>print("<STR_LIT>".format(nit), end="<STR_LIT>")<EOL>print(xk)<EOL>

A sample callback function demonstrating the linprog callback interface.
This callback produces brief output to sys.stdout before each iteration
and after the final iteration of the simplex algorithm.

Parameters
----------
xk : array_like
    The current solution vector.
**kwargs : dict
    A dictionary containing the following parameters:

    tableau : array_like
        The current tableau of the simplex algorithm.
        Its structure is defined in _solve_simplex.
    vars : tuple(str, ...)
        Column headers for each column in tableau.
        "x[i]" for actual variables, "s[i]" for slack surplus variables,
        "a[i]" for artificial variables, and "RHS" for the constraint
        RHS vector.
    phase : int
        The current Phase of the simplex algorithm (1 or 2)
    nit : int
        The current iteration number.
    pivot : tuple(int, int)
        The index of the tableau selected as the next pivot,
        or nan if no pivot exists
    basics : list[tuple(int, float)]
        A list of the current basic variables.
        Each element contains the index of a basic variable and
        its value.
    complete : bool
        True if the simplex algorithm has completed
        (and this is the final call to callback), otherwise False.


def _pivot_row(T, pivcol, phase, tol=<NUM_LIT>):

if phase == <NUM_LIT:1>:<EOL><INDENT>k = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>k = <NUM_LIT:1><EOL><DEDENT>ma = np.ma.masked_where(T[:-k, pivcol] <= tol, T[:-k, pivcol], copy=False)<EOL>if ma.count() == <NUM_LIT:0>:<EOL><INDENT>return False, np.nan<EOL><DEDENT>mb = np.ma.masked_where(T[:-k, pivcol] <= tol, T[:-k, -<NUM_LIT:1>], copy=False)<EOL>q = mb / ma<EOL>return True, np.ma.where(q == q.min())[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>

Given a linear programming simplex tableau, determine the row for the
pivot operation.

Parameters
----------
T : 2D ndarray
    The simplex tableau.
pivcol : int
    The index of the pivot column.
phase : int
    The phase of the simplex algorithm (1 or 2).
tol : float
    Elements in the pivot column smaller than tol will not be considered
    for pivoting.  Nominally this value is zero, but numerical issues
    cause a tolerance about zero to be necessary.

Returns
-------
status: bool
    True if a suitable pivot row was found, otherwise False.  A return
    of False indicates that the linear programming problem is unbounded.
row: int
    The index of the row of the pivot element.  If status is False, row
    will be returned as nan.


def newton(func, x0, fprime=None, args=(), tol=<NUM_LIT>, maxiter=<NUM_LIT:50>,<EOL>fprime2=None):

if tol <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % tol)<EOL><DEDENT>if fprime is not None:<EOL><INDENT>p0 = <NUM_LIT:1.0> * x0<EOL>fder2 = <NUM_LIT:0><EOL>for iter in range(maxiter):<EOL><INDENT>myargs = (p0,) + args<EOL>fder = fprime(*myargs)<EOL>if fder == <NUM_LIT:0>:<EOL><INDENT>msg = "<STR_LIT>"<EOL>warnings.warn(msg, RuntimeWarning)<EOL>return p0<EOL><DEDENT>fval = func(*myargs)<EOL>if fprime2 is not None:<EOL><INDENT>fder2 = fprime2(*myargs)<EOL><DEDENT>if fder2 == <NUM_LIT:0>:<EOL><INDENT>p = p0 - fval / fder<EOL><DEDENT>else:<EOL><INDENT>discr = fder ** <NUM_LIT:2> - <NUM_LIT:2> * fval * fder2<EOL>if discr < <NUM_LIT:0>:<EOL><INDENT>p = p0 - fder / fder2<EOL><DEDENT>else:<EOL><INDENT>p = p0 - <NUM_LIT:2>*fval / (fder + sign(fder) * sqrt(discr))<EOL><DEDENT><DEDENT>if abs(p - p0) < tol:<EOL><INDENT>return p<EOL><DEDENT>p0 = p<EOL><DEDENT><DEDENT>else:<EOL><INDENT>p0 = x0<EOL>if x0 >= <NUM_LIT:0>:<EOL><INDENT>p1 = x0*(<NUM_LIT:1> + <NUM_LIT>) + <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>p1 = x0*(<NUM_LIT:1> + <NUM_LIT>) - <NUM_LIT><EOL><DEDENT>q0 = func(*((p0,) + args))<EOL>q1 = func(*((p1,) + args))<EOL>for iter in range(maxiter):<EOL><INDENT>if q1 == q0:<EOL><INDENT>if p1 != p0:<EOL><INDENT>msg = "<STR_LIT>" % (p1 - p0)<EOL>warnings.warn(msg, RuntimeWarning)<EOL><DEDENT>return (p1 + p0)/<NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>p = p1 - q1*(p1 - p0)/(q1 - q0)<EOL><DEDENT>if abs(p - p1) < tol:<EOL><INDENT>return p<EOL><DEDENT>p0 = p1<EOL>q0 = q1<EOL>p1 = p<EOL>q1 = func(*((p1,) + args))<EOL><DEDENT><DEDENT>msg = "<STR_LIT>" % (maxiter, p)<EOL>raise RuntimeError(msg)<EOL>

Find a zero using the Newton-Raphson or secant method.

Find a zero of the function `func` given a nearby starting point `x0`.
The Newton-Raphson method is used if the derivative `fprime` of `func`
is provided, otherwise the secant method is used.  If the second order
derivate `fprime2` of `func` is provided, parabolic Halley's method
is used.

Parameters
----------
func : function
    The function whose zero is wanted. It must be a function of a
    single variable of the form f(x,a,b,c...), where a,b,c... are extra
    arguments that can be passed in the `args` parameter.
x0 : float
    An initial estimate of the zero that should be somewhere near the
    actual zero.
fprime : function, optional
    The derivative of the function when available and convenient. If it
    is None (default), then the secant method is used.
args : tuple, optional
    Extra arguments to be used in the function call.
tol : float, optional
    The allowable error of the zero value.
maxiter : int, optional
    Maximum number of iterations.
fprime2 : function, optional
    The second order derivative of the function when available and
    convenient. If it is None (default), then the normal Newton-Raphson
    or the secant method is used. If it is given, parabolic Halley's
    method is used.

Returns
-------
zero : float
    Estimated location where function is zero.

See Also
--------
brentq, brenth, ridder, bisect
fsolve : find zeroes in n dimensions.

Notes
-----
The convergence rate of the Newton-Raphson method is quadratic,
the Halley method is cubic, and the secant method is
sub-quadratic.  This means that if the function is well behaved
the actual error in the estimated zero is approximately the square
(cube for Halley) of the requested tolerance up to roundoff
error. However, the stopping criterion used here is the step size
and there is no guarantee that a zero has been found. Consequently
the result should be verified. Safer algorithms are brentq,
brenth, ridder, and bisect, but they all require that the root
first be bracketed in an interval where the function changes
sign. The brentq algorithm is recommended for general use in one
dimensional problems when such an interval has been found.


return self.__scale_arg1 + (trial - <NUM_LIT:0.5>) * self.__scale_arg2<EOL>

scale from a number between 0 and 1 to parameters


r0, r1, r2, r3 = samples[:<NUM_LIT:4>]<EOL>bprime = (self.population[<NUM_LIT:0>] + self.scale *<EOL>(self.population[r0] + self.population[r1]<EOL>- self.population[r2] - self.population[r3]))<EOL>return bprime<EOL>


def _select_samples(self, candidate, number_samples):

idxs = list(range(np.size(self.population, <NUM_LIT:0>)))<EOL>idxs.remove(candidate)<EOL>self.random_number_generator.shuffle(idxs)<EOL>idxs = idxs[:number_samples]<EOL>return idxs<EOL>

obtain random integers from range(np.size(self.population, 0)),
without replacement.  You can't have the original candidate either.


rng = self.random_number_generator<EOL>self.population = rng.random_sample(self.population.shape)<EOL>

Initialises the population at random.  This type of initialization
can possess clustering, Latin Hypercube sampling is generally better.


return self._scale_parameters(self.population[<NUM_LIT:0>])<EOL>

The best solution from the solver

Returns
-------
x - ndarray
    The best solution from the solver.


def leastsq(func, x0, args=(), Dfun=None, full_output=<NUM_LIT:0>,<EOL>col_deriv=<NUM_LIT:0>, ftol=<NUM_LIT>, xtol=<NUM_LIT>,<EOL>gtol=<NUM_LIT:0.0>, maxfev=<NUM_LIT:0>, epsfcn=None, factor=<NUM_LIT:100>, diag=None):

x0 = asarray(x0).flatten()<EOL>n = len(x0)<EOL>if not isinstance(args, tuple):<EOL><INDENT>args = (args,)<EOL><DEDENT>shape, dtype = _check_func('<STR_LIT>', '<STR_LIT>', func, x0, args, n)<EOL>m = shape[<NUM_LIT:0>]<EOL>if n > m:<EOL><INDENT>raise TypeError('<STR_LIT>' % (n, m))<EOL><DEDENT>if epsfcn is None:<EOL><INDENT>epsfcn = finfo(dtype).eps<EOL><DEDENT>if Dfun is None:<EOL><INDENT>if maxfev == <NUM_LIT:0>:<EOL><INDENT>maxfev = <NUM_LIT:200>*(n + <NUM_LIT:1>)<EOL><DEDENT>retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,<EOL>gtol, maxfev, epsfcn, factor, diag)<EOL><DEDENT>else:<EOL><INDENT>if col_deriv:<EOL><INDENT>_check_func('<STR_LIT>', '<STR_LIT>', Dfun, x0, args, n, (n, m))<EOL><DEDENT>else:<EOL><INDENT>_check_func('<STR_LIT>', '<STR_LIT>', Dfun, x0, args, n, (m, n))<EOL><DEDENT>if maxfev == <NUM_LIT:0>:<EOL><INDENT>maxfev = <NUM_LIT:100> * (n + <NUM_LIT:1>)<EOL><DEDENT>retval = _minpack._lmder(func, Dfun, x0, args, full_output, col_deriv,<EOL>ftol, xtol, gtol, maxfev, factor, diag)<EOL><DEDENT>errors = {<NUM_LIT:0>: ["<STR_LIT>", TypeError],<EOL><NUM_LIT:1>: ["<STR_LIT>"<EOL>"<STR_LIT>" % ftol, None],<EOL><NUM_LIT:2>: ["<STR_LIT>"<EOL>"<STR_LIT>" % xtol, None],<EOL><NUM_LIT:3>: ["<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (ftol, xtol), None],<EOL><NUM_LIT:4>: ["<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % gtol, None],<EOL><NUM_LIT:5>: ["<STR_LIT>"<EOL>"<STR_LIT>" % maxfev, ValueError],<EOL><NUM_LIT:6>: ["<STR_LIT>"<EOL>"<STR_LIT>""<STR_LIT>" % ftol,<EOL>ValueError],<EOL><NUM_LIT:7>: ["<STR_LIT>"<EOL>"<STR_LIT>" % xtol,<EOL>ValueError],<EOL><NUM_LIT:8>: ["<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % gtol, ValueError],<EOL>'<STR_LIT>': ["<STR_LIT>", TypeError]}<EOL>info = retval[-<NUM_LIT:1>]    <EOL>if info not in [<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>] and not full_output:<EOL><INDENT>if info in [<NUM_LIT:5>, <NUM_LIT:6>, <NUM_LIT:7>, <NUM_LIT:8>]:<EOL><INDENT>warnings.warn(errors[info][<NUM_LIT:0>], RuntimeWarning)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>raise errors[info][<NUM_LIT:1>](errors[info][<NUM_LIT:0>])<EOL><DEDENT>except KeyError:<EOL><INDENT>raise errors['<STR_LIT>'][<NUM_LIT:1>](errors['<STR_LIT>'][<NUM_LIT:0>])<EOL><DEDENT><DEDENT><DEDENT>mesg = errors[info][<NUM_LIT:0>]<EOL>if full_output:<EOL><INDENT>cov_x = None<EOL>if info in [<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>]:<EOL><INDENT>from numpy.dual import inv<EOL>from numpy.linalg import LinAlgError<EOL>perm = take(eye(n), retval[<NUM_LIT:1>]['<STR_LIT>'] - <NUM_LIT:1>, <NUM_LIT:0>)<EOL>r = triu(transpose(retval[<NUM_LIT:1>]['<STR_LIT>'])[:n, :])<EOL>R = dot(r, perm)<EOL>try:<EOL><INDENT>cov_x = inv(dot(transpose(R), R))<EOL><DEDENT>except (LinAlgError, ValueError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return (retval[<NUM_LIT:0>], cov_x) + retval[<NUM_LIT:1>:-<NUM_LIT:1>] + (mesg, info)<EOL><DEDENT>else:<EOL><INDENT>return (retval[<NUM_LIT:0>], info)<EOL><DEDENT>

Minimize the sum of squares of a set of equations.

::

    x = arg min(sum(func(y)**2,axis=0))
             y

Parameters
----------
func : callable
    should take at least one (possibly length N vector) argument and
    returns M floating point numbers. It must not return NaNs or
    fitting might fail.
x0 : ndarray
    The starting estimate for the minimization.
args : tuple
    Any extra arguments to func are placed in this tuple.
Dfun : callable
    A function or method to compute the Jacobian of func with derivatives
    across the rows. If this is None, the Jacobian will be estimated.
full_output : bool
    non-zero to return all optional outputs.
col_deriv : bool
    non-zero to specify that the Jacobian function computes derivatives
    down the columns (faster, because there is no transpose operation).
ftol : float
    Relative error desired in the sum of squares.
xtol : float
    Relative error desired in the approximate solution.
gtol : float
    Orthogonality desired between the function vector and the columns of
    the Jacobian.
maxfev : int
    The maximum number of calls to the function. If zero, then 100*(N+1) is
    the maximum where N is the number of elements in x0.
epsfcn : float
    A variable used in determining a suitable step length for the forward-
    difference approximation of the Jacobian (for Dfun=None).
    Normally the actual step length will be sqrt(epsfcn)*x
    If epsfcn is less than the machine precision, it is assumed that the
    relative errors are of the order of the machine precision.
factor : float
    A parameter determining the initial step bound
    (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``.
diag : sequence
    N positive entries that serve as a scale factors for the variables.

Returns
-------
x : ndarray
    The solution (or the result of the last iteration for an unsuccessful
    call).
cov_x : ndarray
    Uses the fjac and ipvt optional outputs to construct an
    estimate of the jacobian around the solution. None if a
    singular matrix encountered (indicates very flat curvature in
    some direction).  This matrix must be multiplied by the
    residual variance to get the covariance of the
    parameter estimates -- see curve_fit.
infodict : dict
    a dictionary of optional outputs with the key s:

    ``nfev``
        The number of function calls
    ``fvec``
        The function evaluated at the output
    ``fjac``
        A permutation of the R matrix of a QR
        factorization of the final approximate
        Jacobian matrix, stored column wise.
        Together with ipvt, the covariance of the
        estimate can be approximated.
    ``ipvt``
        An integer array of length N which defines
        a permutation matrix, p, such that
        fjac*p = q*r, where r is upper triangular
        with diagonal elements of nonincreasing
        magnitude. Column j of p is column ipvt(j)
        of the identity matrix.
    ``qtf``
        The vector (transpose(q) * fvec).

mesg : str
    A string message giving information about the cause of failure.
ier : int
    An integer flag.  If it is equal to 1, 2, 3 or 4, the solution was
    found.  Otherwise, the solution was not found. In either case, the
    optional output variable 'mesg' gives more information.

Notes
-----
"leastsq" is a wrapper around MINPACK's lmdif and lmder algorithms.

cov_x is a Jacobian approximation to the Hessian of the least squares
objective function.
This approximation assumes that the objective function is based on the
difference between some observed target data (ydata) and a (non-linear)
function of the parameters `f(xdata, params)` ::

       func(params) = ydata - f(xdata, params)

so that the objective function is ::

       min   sum((ydata - f(xdata, params))**2, axis=0)
     params


def fsolve(func, x0, args=(), fprime=None, full_output=<NUM_LIT:0>,<EOL>col_deriv=<NUM_LIT:0>, xtol=<NUM_LIT>, maxfev=<NUM_LIT:0>, band=None,<EOL>epsfcn=None, factor=<NUM_LIT:100>, diag=None):

options = {'<STR_LIT>': col_deriv,<EOL>'<STR_LIT>': xtol,<EOL>'<STR_LIT>': maxfev,<EOL>'<STR_LIT>': band,<EOL>'<STR_LIT>': epsfcn,<EOL>'<STR_LIT>': factor,<EOL>'<STR_LIT>': diag,<EOL>'<STR_LIT>': full_output}<EOL>res = _root_hybr(func, x0, args, jac=fprime, **options)<EOL>if full_output:<EOL><INDENT>x = res['<STR_LIT:x>']<EOL>info = dict((k, res.get(k))<EOL>for k in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:r>', '<STR_LIT>') if k in res)<EOL>info['<STR_LIT>'] = res['<STR_LIT>']<EOL>return x, info, res['<STR_LIT:status>'], res['<STR_LIT:message>']<EOL><DEDENT>else:<EOL><INDENT>return res['<STR_LIT:x>']<EOL><DEDENT>

Find the roots of a function.

Return the roots of the (non-linear) equations defined by
``func(x) = 0`` given a starting estimate.

Parameters
----------
func : callable ``f(x, *args)``
    A function that takes at least one (possibly vector) argument.
x0 : ndarray
    The starting estimate for the roots of ``func(x) = 0``.
args : tuple, optional
    Any extra arguments to `func`.
fprime : callable(x), optional
    A function to compute the Jacobian of `func` with derivatives
    across the rows. By default, the Jacobian will be estimated.
full_output : bool, optional
    If True, return optional outputs.
col_deriv : bool, optional
    Specify whether the Jacobian function computes derivatives down
    the columns (faster, because there is no transpose operation).
xtol : float
    The calculation will terminate if the relative error between two
    consecutive iterates is at most `xtol`.
maxfev : int, optional
    The maximum number of calls to the function. If zero, then
    ``100*(N+1)`` is the maximum where N is the number of elements
    in `x0`.
band : tuple, optional
    If set to a two-sequence containing the number of sub- and
    super-diagonals within the band of the Jacobi matrix, the
    Jacobi matrix is considered banded (only for ``fprime=None``).
epsfcn : float, optional
    A suitable step length for the forward-difference
    approximation of the Jacobian (for ``fprime=None``). If
    `epsfcn` is less than the machine precision, it is assumed
    that the relative errors in the functions are of the order of
    the machine precision.
factor : float, optional
    A parameter determining the initial step bound
    (``factor * || diag * x||``).  Should be in the interval
    ``(0.1, 100)``.
diag : sequence, optional
    N positive entries that serve as a scale factors for the
    variables.

Returns
-------
x : ndarray
    The solution (or the result of the last iteration for
    an unsuccessful call).
infodict : dict
    A dictionary of optional outputs with the keys:

    ``nfev``
        number of function calls
    ``njev``
        number of Jacobian calls
    ``fvec``
        function evaluated at the output
    ``fjac``
        the orthogonal matrix, q, produced by the QR
        factorization of the final approximate Jacobian
        matrix, stored column wise
    ``r``
        upper triangular matrix produced by QR factorization
        of the same matrix
    ``qtf``
        the vector ``(transpose(q) * fvec)``

ier : int
    An integer flag.  Set to 1 if a solution was found, otherwise refer
    to `mesg` for more information.
mesg : str
    If no solution is found, `mesg` details the cause of failure.

See Also
--------
root : Interface to root finding algorithms for multivariate
functions. See the 'hybr' `method` in particular.

Notes
-----
``fsolve`` is a wrapper around MINPACK's hybrd and hybrj algorithms.


x0 = asfarray(x)<EOL>f0 = atleast_1d(func(*((x0,)+args)))<EOL>jac = zeros([len(x0),len(f0)])<EOL>dx = zeros(len(x0))<EOL>for i in range(len(x0)):<EOL><INDENT>dx[i] = epsilon<EOL>jac[i] = (func(*((x0+dx,)+args)) - f0)/epsilon<EOL>dx[i] = <NUM_LIT:0.0><EOL><DEDENT>return jac.transpose()<EOL>

Approximate the Jacobian matrix of a callable function.

Parameters
----------
x : array_like
    The state vector at which to compute the Jacobian matrix.
func : callable f(x,*args)
    The vector-valued function.
epsilon : float
    The perturbation used to determine the partial derivatives.
args : sequence
    Additional arguments passed to func.

Returns
-------
An array of dimensions ``(lenf, lenx)`` where ``lenf`` is the length
of the outputs of `func`, and ``lenx`` is the number of elements in
`x`.

Notes
-----
The approximation is done using forward differences.


def fourier_shift(input, shift, n=-<NUM_LIT:1>, axis=-<NUM_LIT:1>, output=None):

input = numpy.asarray(input)<EOL>output, return_value = _get_output_fourier_complex(output, input)<EOL>axis = _ni_support._check_axis(axis, input.ndim)<EOL>shifts = _ni_support._normalize_sequence(shift, input.ndim)<EOL>shifts = numpy.asarray(shifts, dtype=numpy.float64)<EOL>if not shifts.flags.contiguous:<EOL><INDENT>shifts = shifts.copy()<EOL><DEDENT>_nd_image.fourier_shift(input, shifts, n, axis, output)<EOL>return return_value<EOL>

Multi-dimensional fourier shift filter.

The array is multiplied with the fourier transform of a shift operation.

Parameters
----------
input : array_like
    The input array.
shift : float or sequence
    The size of the box used for filtering.
    If a float, `shift` is the same for all axes. If a sequence, `shift`
    has to contain one value for each axis.
n : int, optional
    If `n` is negative (default), then the input is assumed to be the
    result of a complex fft.
    If `n` is larger than or equal to zero, the input is assumed to be the
    result of a real fft, and `n` gives the length of the array before
    transformation along the real transform direction.
axis : int, optional
    The axis of the real transform.
output : ndarray, optional
    If given, the result of shifting the input is placed in this array.
    None is returned in this case.

Returns
-------
fourier_shift : ndarray or None
    The shifted input. If `output` is given as a parameter, None is
    returned.


def fourier_gaussian(input, sigma, n=-<NUM_LIT:1>, axis=-<NUM_LIT:1>, output=None):

input = numpy.asarray(input)<EOL>output, return_value = _get_output_fourier(output, input)<EOL>axis = _ni_support._check_axis(axis, input.ndim)<EOL>sigmas = _ni_support._normalize_sequence(sigma, input.ndim)<EOL>sigmas = numpy.asarray(sigmas, dtype=numpy.float64)<EOL>if not sigmas.flags.contiguous:<EOL><INDENT>sigmas = sigmas.copy()<EOL><DEDENT>_nd_image.fourier_filter(input, sigmas, n, axis, output, <NUM_LIT:0>)<EOL>return return_value<EOL>

Multi-dimensional Gaussian fourier filter.

The array is multiplied with the fourier transform of a Gaussian
kernel.

Parameters
----------
input : array_like
    The input array.
sigma : float or sequence
    The sigma of the Gaussian kernel. If a float, `sigma` is the same for
    all axes. If a sequence, `sigma` has to contain one value for each
    axis.
n : int, optional
    If `n` is negative (default), then the input is assumed to be the
    result of a complex fft.
    If `n` is larger than or equal to zero, the input is assumed to be the
    result of a real fft, and `n` gives the length of the array before
    transformation along the real transform direction.
axis : int, optional
    The axis of the real transform.
output : ndarray, optional
    If given, the result of filtering the input is placed in this array.
    None is returned in this case.

Returns
-------
fourier_gaussian : ndarray or None
    The filtered input. If `output` is given as a parameter, None is
    returned.


def median(input, labels=None, index=None):

return _select(input, labels, index, find_median=True)[<NUM_LIT:0>]<EOL>

Calculate the median of the values of an array over labeled regions.

Parameters
----------
input : array_like
    Array_like of values. For each region specified by `labels`, the
    median value of `input` over the region is computed.
labels : array_like, optional
    An array_like of integers marking different regions over which the
    median value of `input` is to be computed. `labels` must have the
    same shape as `input`. If `labels` is not specified, the median
    over the whole array is returned.
index : array_like, optional
    A list of region labels that are taken into account for computing the
    medians. If index is None, the median over all elements where `labels`
    is non-zero is returned.

Returns
-------
median : float or list of floats
    List of medians of `input` over the regions determined by `labels` and
    whose index is in `index`. If `index` or `labels` are not specified, a
    float is returned: the median value of `input` if `labels` is None,
    and the median value of elements where `labels` is greater than zero
    if `index` is None.

See also
--------
label, minimum, maximum, extrema, sum, mean, variance, standard_deviation

Notes
-----
The function returns a Python list and not a Numpy array, use
`np.array` to convert the list to an array.

Examples
--------
>>> a = np.array([[1, 2, 0, 1],
...               [5, 3, 0, 4],
...               [0, 0, 0, 7],
...               [9, 3, 0, 0]])
>>> labels, labels_nb = ndimage.label(a)
>>> labels
array([[1, 1, 0, 2],
       [1, 1, 0, 2],
       [0, 0, 0, 2],
       [3, 3, 0, 0]])
>>> ndimage.median(a, labels=labels, index=np.arange(1, labels_nb + 1))
[2.5, 4.0, 6.0]
>>> ndimage.median(a)
1.0
>>> ndimage.median(a, labels=labels)
3.0


def center_of_mass(input, labels=None, index=None):

normalizer = sum(input, labels, index)<EOL>grids = numpy.ogrid[[slice(<NUM_LIT:0>, i) for i in input.shape]]<EOL>results = [sum(input * grids[dir].astype(float), labels, index) / normalizer<EOL>for dir in range(input.ndim)]<EOL>if numpy.isscalar(results[<NUM_LIT:0>]):<EOL><INDENT>return tuple(results)<EOL><DEDENT>return [tuple(v) for v in numpy.array(results).T]<EOL>

Calculate the center of mass of the values of an array at labels.

Parameters
----------
input : ndarray
    Data from which to calculate center-of-mass.
labels : ndarray, optional
    Labels for objects in `input`, as generated by `ndimage.label`.
    Only used with `index`.  Dimensions must be the same as `input`.
index : int or sequence of ints, optional
    Labels for which to calculate centers-of-mass. If not specified,
    all labels greater than zero are used.  Only used with `labels`.

Returns
-------
center_of_mass : tuple, or list of tuples
    Coordinates of centers-of-mass.

Examples
--------
>>> a = np.array(([0,0,0,0],
                  [0,1,1,0],
                  [0,1,1,0],
                  [0,1,1,0]))
>>> from scipy import ndimage
>>> ndimage.measurements.center_of_mass(a)
(2.0, 1.5)

Calculation of multiple objects in an image

>>> b = np.array(([0,1,1,0],
                  [0,1,0,0],
                  [0,0,0,0],
                  [0,0,1,1],
                  [0,0,1,1]))
>>> lbl = ndimage.label(b)[0]
>>> ndimage.measurements.center_of_mass(b, lbl, [1,2])
[(0.33333333333333331, 1.3333333333333333), (3.5, 2.5)]


def labeled_comprehension(input, labels, index, func, out_dtype, default, pass_positions=False):

as_scalar = numpy.isscalar(index)<EOL>input = numpy.asarray(input)<EOL>if pass_positions:<EOL><INDENT>positions = numpy.arange(input.size).reshape(input.shape)<EOL><DEDENT>if labels is None:<EOL><INDENT>if index is not None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not pass_positions:<EOL><INDENT>return func(input.ravel())<EOL><DEDENT>else:<EOL><INDENT>return func(input.ravel(), positions.ravel())<EOL><DEDENT><DEDENT>try:<EOL><INDENT>input, labels = numpy.broadcast_arrays(input, labels)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if index is None:<EOL><INDENT>if not pass_positions:<EOL><INDENT>return func(input[labels > <NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>return func(input[labels > <NUM_LIT:0>], positions[labels > <NUM_LIT:0>])<EOL><DEDENT><DEDENT>index = numpy.atleast_1d(index)<EOL>if np.any(index.astype(labels.dtype).astype(index.dtype) != index):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(index.dtype, labels.dtype))<EOL><DEDENT>index = index.astype(labels.dtype)<EOL>lo = index.min()<EOL>hi = index.max()<EOL>mask = (labels >= lo) & (labels <= hi)<EOL>labels = labels[mask]<EOL>input = input[mask]<EOL>if pass_positions:<EOL><INDENT>positions = positions[mask]<EOL><DEDENT>label_order = labels.argsort()<EOL>labels = labels[label_order]<EOL>input = input[label_order]<EOL>if pass_positions:<EOL><INDENT>positions = positions[label_order]<EOL><DEDENT>index_order = index.argsort()<EOL>sorted_index = index[index_order]<EOL>def do_map(inputs, output):<EOL><INDENT>"""<STR_LIT>"""<EOL>nidx = sorted_index.size<EOL>lo = numpy.searchsorted(labels, sorted_index, side='<STR_LIT:left>')<EOL>hi = numpy.searchsorted(labels, sorted_index, side='<STR_LIT:right>')<EOL>for i, l, h in zip(range(nidx), lo, hi):<EOL><INDENT>if l == h:<EOL><INDENT>continue<EOL><DEDENT>output[i] = func(*[inp[l:h] for inp in inputs])<EOL><DEDENT><DEDENT>temp = numpy.empty(index.shape, out_dtype)<EOL>temp[:] = default<EOL>if not pass_positions:<EOL><INDENT>do_map([input], temp)<EOL><DEDENT>else:<EOL><INDENT>do_map([input, positions], temp)<EOL><DEDENT>output = numpy.zeros(index.shape, out_dtype)<EOL>output[index_order] = temp<EOL>if as_scalar:<EOL><INDENT>output = output[<NUM_LIT:0>]<EOL><DEDENT>return output<EOL>

Roughly equivalent to [func(input[labels == i]) for i in index].

Sequentially applies an arbitrary function (that works on array_like input)
to subsets of an n-D image array specified by `labels` and `index`.
The option exists to provide the function with positional parameters as the
second argument.

Parameters
----------
input : array_like
    Data from which to select `labels` to process.
labels : array_like or None
    Labels to objects in `input`.
    If not None, array must be same shape as `input`.
    If None, `func` is applied to raveled `input`.
index : int, sequence of ints or None
    Subset of `labels` to which to apply `func`.
    If a scalar, a single value is returned.
    If None, `func` is applied to all non-zero values of `labels`.
func : callable
    Python function to apply to `labels` from `input`.
out_dtype : dtype
    Dtype to use for `result`.
default : int, float or None
    Default return value when a element of `index` does not exist
    in `labels`.
pass_positions : bool, optional
    If True, pass linear indices to `func` as a second argument.
    Default is False.

Returns
-------
result : ndarray
    Result of applying `func` to each of `labels` to `input` in `index`.

Examples
--------
>>> a = np.array([[1, 2, 0, 0],
                  [5, 3, 0, 4],
                  [0, 0, 0, 7],
                  [9, 3, 0, 0]])
>>> from scipy import ndimage
>>> lbl, nlbl = ndimage.label(a)
>>> lbls = np.arange(1, nlbl+1)
>>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, 0)
array([ 2.75,  5.5 ,  6.  ])

Falling back to `default`:

>>> lbls = np.arange(1, nlbl+2)
>>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, -1)
array([ 2.75,  5.5 ,  6.  , -1.  ])

Passing positions:

>>> def fn(val, pos):
...     print("fn says: %s : %s" % (val, pos))
...     return (val.sum()) if (pos.sum() % 2 == 0) else (-val.sum())
...
>>> ndimage.labeled_comprehension(a, lbl, lbls, fn, float, 0, True)
fn says: [1 2 5 3] : [0 1 4 5]
fn says: [4 7] : [7 11]
fn says: [9 3] : [12 13]
array([ 11.,  11., -12.])


def minimum_position(input, labels=None, index=None):

dims = numpy.array(numpy.asarray(input).shape)<EOL>dim_prod = numpy.cumprod([<NUM_LIT:1>] + list(dims[:<NUM_LIT:0>:-<NUM_LIT:1>]))[::-<NUM_LIT:1>]<EOL>result = _select(input, labels, index, find_min_positions=True)[<NUM_LIT:0>]<EOL>if numpy.isscalar(result):<EOL><INDENT>return tuple((result // dim_prod) % dims)<EOL><DEDENT>return [tuple(v) for v in (result.reshape(-<NUM_LIT:1>, <NUM_LIT:1>) // dim_prod) % dims]<EOL>

Find the positions of the minimums of the values of an array at labels.

Parameters
----------
input : array_like
    Array_like of values.
labels : array_like, optional
    An array of integers marking different regions over which the
    position of the minimum value of `input` is to be computed.
    `labels` must have the same shape as `input`. If `labels` is not
    specified, the location of the first minimum over the whole
    array is returned.

    The `labels` argument only works when `index` is specified.
index : array_like, optional
    A list of region labels that are taken into account for finding the
    location of the minima. If `index` is None, the ``first`` minimum
    over all elements where `labels` is non-zero is returned.

    The `index` argument only works when `labels` is specified.

Returns
-------
output : list of tuples of ints
    Tuple of ints or list of tuples of ints that specify the location
    of minima of `input` over the regions determined by `labels` and
    whose index is in `index`.

    If `index` or `labels` are not specified, a tuple of ints is
    returned specifying the location of the first minimal value of `input`.

See also
--------
label, minimum, median, maximum_position, extrema, sum, mean, variance,
standard_deviation


def label(input, structure=None, output=None):

input = numpy.asarray(input)<EOL>if numpy.iscomplexobj(input):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if structure is None:<EOL><INDENT>structure = morphology.generate_binary_structure(input.ndim, <NUM_LIT:1>)<EOL><DEDENT>structure = numpy.asarray(structure, dtype=bool)<EOL>if structure.ndim != input.ndim:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>for ii in structure.shape:<EOL><INDENT>if ii != <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>need_64bits = input.size >= (<NUM_LIT:2>**<NUM_LIT> - <NUM_LIT:2>)<EOL>if isinstance(output, numpy.ndarray):<EOL><INDENT>if output.shape != input.shape:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>caller_provided_output = True<EOL><DEDENT>else:<EOL><INDENT>caller_provided_output = False<EOL>if output is None:<EOL><INDENT>output = np.empty(input.shape, np.intp if need_64bits else np.int32)<EOL><DEDENT>else:<EOL><INDENT>output = np.empty(input.shape, output)<EOL><DEDENT><DEDENT>if input.ndim == <NUM_LIT:0> or input.size == <NUM_LIT:0>:<EOL><INDENT>if input.ndim == <NUM_LIT:0>:<EOL><INDENT>maxlabel = <NUM_LIT:1> if (input != <NUM_LIT:0>) else <NUM_LIT:0><EOL>output[...] = maxlabel<EOL><DEDENT>else:<EOL><INDENT>maxlabel = <NUM_LIT:0><EOL><DEDENT>if caller_provided_output:<EOL><INDENT>return maxlabel<EOL><DEDENT>else:<EOL><INDENT>return output, maxlabel<EOL><DEDENT><DEDENT>try:<EOL><INDENT>max_label = _ni_label._label(input, structure, output)<EOL><DEDENT>except _ni_label.NeedMoreBits:<EOL><INDENT>tmp_output = np.empty(input.shape, np.intp if need_64bits else np.int32)<EOL>max_label = _ni_label._label(input, structure, tmp_output)<EOL>output[...] = tmp_output[...]<EOL>if not np.all(output == tmp_output):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT><DEDENT>if caller_provided_output:<EOL><INDENT>return max_label<EOL><DEDENT>else:<EOL><INDENT>return output, max_label<EOL><DEDENT>

Label features in an array.

Parameters
----------
input : array_like
    An array-like object to be labeled.  Any non-zero values in `input` are
    counted as features and zero values are considered the background.
structure : array_like, optional
    A structuring element that defines feature connections.
    `structure` must be symmetric.  If no structuring element is provided,
    one is automatically generated with a squared connectivity equal to
    one.  That is, for a 2-D `input` array, the default structuring element
    is::

        [[0,1,0],
         [1,1,1],
         [0,1,0]]

output : (None, data-type, array_like), optional
    If `output` is a data type, it specifies the type of the resulting
    labeled feature array
    If `output` is an array-like object, then `output` will be updated
    with the labeled features from this function.  This function can
    operate in-place, by passing output=input.
    Note that the output must be able to store the largest label, or this
    function will raise an Exception.

Returns
-------
label : ndarray or int
    An integer ndarray where each unique feature in `input` has a unique
    label in the returned array.
num_features : int
    How many objects were found.

    If `output` is None, this function returns a tuple of
    (`labeled_array`, `num_features`).

    If `output` is a ndarray, then it will be updated with values in
    `labeled_array` and only `num_features` will be returned by this
    function.

See Also
--------
find_objects : generate a list of slices for the labeled features (or
               objects); useful for finding features' position or
               dimensions

Examples
--------
Create an image with some features, then label it using the default
(cross-shaped) structuring element:

>>> a = np.array([[0,0,1,1,0,0],
...               [0,0,0,1,0,0],
...               [1,1,0,0,1,0],
...               [0,0,0,1,0,0]])
>>> labeled_array, num_features = label(a)

Each of the 4 features are labeled with a different integer:

>>> print(num_features)
4
>>> print(labeled_array)
array([[0, 0, 1, 1, 0, 0],
       [0, 0, 0, 1, 0, 0],
       [2, 2, 0, 0, 3, 0],
       [0, 0, 0, 4, 0, 0]])

Generate a structuring element that will consider features connected even
if they touch diagonally:

>>> s = generate_binary_structure(2,2)

or,

>>> s = [[1,1,1],
         [1,1,1],
         [1,1,1]]

Label the image using the new structuring element:

>>> labeled_array, num_features = label(a, structure=s)

Show the 2 labeled features (note that features 1, 3, and 4 from above are
now considered a single feature):

>>> print(num_features)
2
>>> print(labeled_array)
array([[0, 0, 1, 1, 0, 0],
       [0, 0, 0, 1, 0, 0],
       [2, 2, 0, 0, 1, 0],
       [0, 0, 0, 1, 0, 0]])


@docfiller<EOL>def convolve(input, weights, output=None, mode='<STR_LIT>', cval=<NUM_LIT:0.0>,<EOL>origin=<NUM_LIT:0>):

return _correlate_or_convolve(input, weights, output, mode, cval,<EOL>origin, True)<EOL>

Multidimensional convolution.

The array is convolved with the given kernel.

Parameters
----------
input : array_like
    Input array to filter.
weights : array_like
    Array of weights, same number of dimensions as input
output : ndarray, optional
    The `output` parameter passes an array in which to store the
    filter output.
mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
    the `mode` parameter determines how the array borders are
    handled. For 'constant' mode, values beyond borders are set to be
    `cval`. Default is 'reflect'.
cval : scalar, optional
    Value to fill past edges of input if `mode` is 'constant'. Default
    is 0.0
origin : array_like, optional
    The `origin` parameter controls the placement of the filter.
    Default is 0.

Returns
-------
result : ndarray
    The result of convolution of `input` with `weights`.

See Also
--------
correlate : Correlate an image with a kernel.

Notes
-----
Each value in result is :math:`C_i = \\sum_j{I_{i+j-k} W_j}`, where
W is the `weights` kernel,
j is the n-D spatial index over :math:`W`,
I is the `input` and k is the coordinate of the center of
W, specified by `origin` in the input parameters.

Examples
--------
Perhaps the simplest case to understand is ``mode='constant', cval=0.0``,
because in this case borders (i.e. where the `weights` kernel, centered
on any one value, extends beyond an edge of `input`.

>>> a = np.array([[1, 2, 0, 0],
....    [5, 3, 0, 4],
....    [0, 0, 0, 7],
....    [9, 3, 0, 0]])
>>> k = np.array([[1,1,1],[1,1,0],[1,0,0]])
>>> from scipy import ndimage
>>> ndimage.convolve(a, k, mode='constant', cval=0.0)
array([[11, 10,  7,  4],
       [10,  3, 11, 11],
       [15, 12, 14,  7],
       [12,  3,  7,  0]])

Setting ``cval=1.0`` is equivalent to padding the outer edge of `input`
with 1.0's (and then extracting only the original region of the result).

>>> ndimage.convolve(a, k, mode='constant', cval=1.0)
array([[13, 11,  8,  7],
       [11,  3, 11, 14],
       [16, 12, 14, 10],
       [15,  6, 10,  5]])

With ``mode='reflect'`` (the default), outer values are reflected at the
edge of `input` to fill in missing values.

>>> b = np.array([[2, 0, 0],
                  [1, 0, 0],
                  [0, 0, 0]])
>>> k = np.array([[0,1,0],[0,1,0],[0,1,0]])
>>> ndimage.convolve(b, k, mode='reflect')
array([[5, 0, 0],
       [3, 0, 0],
       [1, 0, 0]])

This includes diagonally at the corners.

>>> k = np.array([[1,0,0],[0,1,0],[0,0,1]])
>>> ndimage.convolve(b, k)
array([[4, 2, 0],
       [3, 2, 0],
       [1, 1, 0]])

With ``mode='nearest'``, the single nearest value in to an edge in
`input` is repeated as many times as needed to match the overlapping
`weights`.

>>> c = np.array([[2, 0, 1],
                  [1, 0, 0],
                  [0, 0, 0]])
>>> k = np.array([[0, 1, 0],
                  [0, 1, 0],
                  [0, 1, 0],
                  [0, 1, 0],
                  [0, 1, 0]])
>>> ndimage.convolve(c, k, mode='nearest')
array([[7, 0, 3],
       [5, 0, 2],
       [3, 0, 1]])


@docfiller<EOL>def prewitt(input, axis=-<NUM_LIT:1>, output=None, mode="<STR_LIT>", cval=<NUM_LIT:0.0>):

input = numpy.asarray(input)<EOL>axis = _ni_support._check_axis(axis, input.ndim)<EOL>output, return_value = _ni_support._get_output(output, input)<EOL>correlate1d(input, [-<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>], axis, output, mode, cval, <NUM_LIT:0>)<EOL>axes = [ii for ii in range(input.ndim) if ii != axis]<EOL>for ii in axes:<EOL><INDENT>correlate1d(output, [<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>], ii, output, mode, cval, <NUM_LIT:0>,)<EOL><DEDENT>return return_value<EOL>

Calculate a Prewitt filter.

    Parameters
    ----------
    %(input)s
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s


@docfiller<EOL>def rank_filter(input, rank, size=None, footprint=None, output=None,<EOL>mode="<STR_LIT>", cval=<NUM_LIT:0.0>, origin=<NUM_LIT:0>):

return _rank_filter(input, rank, size, footprint, output, mode, cval,<EOL>origin, '<STR_LIT>')<EOL>

Calculates a multi-dimensional rank filter.

    Parameters
    ----------
    %(input)s
    rank : integer
        The rank parameter may be less then zero, i.e., rank = -1
        indicates the largest element.
    %(size_foot)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s


@docfiller<EOL>def minimum_filter1d(input, size, axis=-<NUM_LIT:1>, output=None,<EOL>mode="<STR_LIT>", cval=<NUM_LIT:0.0>, origin=<NUM_LIT:0>):

input = numpy.asarray(input)<EOL>if numpy.iscomplexobj(input):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>axis = _ni_support._check_axis(axis, input.ndim)<EOL>if size < <NUM_LIT:1>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>output, return_value = _ni_support._get_output(output, input)<EOL>if (size // <NUM_LIT:2> + origin < <NUM_LIT:0>) or (size // <NUM_LIT:2> + origin >= size):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>mode = _ni_support._extend_mode_to_code(mode)<EOL>_nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,<EOL>origin, <NUM_LIT:1>)<EOL>return return_value<EOL>

Calculate a one-dimensional minimum filter along the given axis.

    The lines of the array along the given axis are filtered with a
    minimum filter of given size.

    Parameters
    ----------
    %(input)s
    size : int
        length along which to calculate 1D minimum
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s

    Notes
    -----
    This function implements the MINLIST algorithm [1]_, as described by
    Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
    the `input` length, regardless of filter size.

    References
    ----------
    .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
    .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html


@docfiller<EOL>def generic_gradient_magnitude(input, derivative, output=None,<EOL>mode="<STR_LIT>", cval=<NUM_LIT:0.0>,<EOL>extra_arguments=(), extra_keywords = None):

if extra_keywords is None:<EOL><INDENT>extra_keywords = {}<EOL><DEDENT>input = numpy.asarray(input)<EOL>output, return_value = _ni_support._get_output(output, input)<EOL>axes = list(range(input.ndim))<EOL>if len(axes) > <NUM_LIT:0>:<EOL><INDENT>derivative(input, axes[<NUM_LIT:0>], output, mode, cval,<EOL>*extra_arguments, **extra_keywords)<EOL>numpy.multiply(output, output, output)<EOL>for ii in range(<NUM_LIT:1>, len(axes)):<EOL><INDENT>tmp = derivative(input, axes[ii], output.dtype, mode, cval,<EOL>*extra_arguments, **extra_keywords)<EOL>numpy.multiply(tmp, tmp, tmp)<EOL>output += tmp<EOL><DEDENT>if NumpyVersion(numpy.__version__) > '<STR_LIT>':<EOL><INDENT>numpy.sqrt(output, output, casting='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>numpy.sqrt(output, output)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>output[...] = input[...]<EOL><DEDENT>return return_value<EOL>

Gradient magnitude using a provided gradient function.

    Parameters
    ----------
    %(input)s
    derivative : callable
        Callable with the following signature::

            derivative(input, axis, output, mode, cval,
                       *extra_arguments, **extra_keywords)

        See `extra_arguments`, `extra_keywords` below.
        `derivative` can assume that `input` and `output` are ndarrays.
        Note that the output from `derivative` is modified inplace;
        be careful to copy important inputs before returning them.
    %(output)s
    %(mode)s
    %(cval)s
    %(extra_keywords)s
    %(extra_arguments)s


@docfiller<EOL>def generic_filter1d(input, function, filter_size, axis=-<NUM_LIT:1>,<EOL>output=None, mode="<STR_LIT>", cval=<NUM_LIT:0.0>, origin=<NUM_LIT:0>,<EOL>extra_arguments=(), extra_keywords = None):

if extra_keywords is None:<EOL><INDENT>extra_keywords = {}<EOL><DEDENT>input = numpy.asarray(input)<EOL>if numpy.iscomplexobj(input):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>output, return_value = _ni_support._get_output(output, input)<EOL>if filter_size < <NUM_LIT:1>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>axis = _ni_support._check_axis(axis, input.ndim)<EOL>if (filter_size // <NUM_LIT:2> + origin < <NUM_LIT:0>) or (filter_size // <NUM_LIT:2> + origin >=<EOL>filter_size):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>mode = _ni_support._extend_mode_to_code(mode)<EOL>_nd_image.generic_filter1d(input, function, filter_size, axis, output,<EOL>mode, cval, origin, extra_arguments, extra_keywords)<EOL>return return_value<EOL>

Calculate a one-dimensional filter along the given axis.

    `generic_filter1d` iterates over the lines of the array, calling the
    given function at each line. The arguments of the line are the
    input line, and the output line. The input and output lines are 1D
    double arrays.  The input line is extended appropriately according
    to the filter size and origin. The output line must be modified
    in-place with the result.

    Parameters
    ----------
    %(input)s
    function : callable
        Function to apply along given axis.
    filter_size : scalar
        Length of the filter.
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s
    %(extra_arguments)s
    %(extra_keywords)s


@docfiller<EOL>def convolve1d(input, weights, axis=-<NUM_LIT:1>, output=None, mode="<STR_LIT>",<EOL>cval=<NUM_LIT:0.0>, origin=<NUM_LIT:0>):

weights = weights[::-<NUM_LIT:1>]<EOL>origin = -origin<EOL>if not len(weights) & <NUM_LIT:1>:<EOL><INDENT>origin -= <NUM_LIT:1><EOL><DEDENT>return correlate1d(input, weights, axis, output, mode, cval, origin)<EOL>

Calculate a one-dimensional convolution along the given axis.

    The lines of the array along the given axis are convolved with the
    given weights.

    Parameters
    ----------
    %(input)s
    weights : ndarray
        One-dimensional sequence of numbers.
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s

    Returns
    -------
    convolve1d : ndarray
        Convolved array with same shape as input


def _geometric_transform(input, mapping, coordinates, matrix, offset, output,<EOL>order, mode, cval, extra_arguments, extra_keywords):

_nd_image.geometric_transform(<EOL>input, mapping, coordinates, matrix, offset, output,<EOL>order, mode, cval, extra_arguments, extra_keywords)<EOL>if output is not None and not output.dtype.isnative:<EOL><INDENT>output.byteswap(True)<EOL><DEDENT>return output<EOL>

Wrapper around _nd_image.geometric_transform to work around
endianness issues


def spline_filter1d(input, order=<NUM_LIT:3>, axis=-<NUM_LIT:1>, output=numpy.float64):

if order < <NUM_LIT:0> or order > <NUM_LIT:5>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>input = numpy.asarray(input)<EOL>if numpy.iscomplexobj(input):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>output, return_value = _ni_support._get_output(output, input)<EOL>if order in [<NUM_LIT:0>, <NUM_LIT:1>]:<EOL><INDENT>output[...] = numpy.array(input)<EOL><DEDENT>else:<EOL><INDENT>axis = _ni_support._check_axis(axis, input.ndim)<EOL>_nd_image.spline_filter1d(input, order, axis, output)<EOL><DEDENT>return return_value<EOL>

Calculates a one-dimensional spline filter along the given axis.

The lines of the array along the given axis are filtered by a
spline filter. The order of the spline must be >= 2 and <= 5.

Parameters
----------
input : array_like
    The input array.
order : int, optional
    The order of the spline, default is 3.
axis : int, optional
    The axis along which the spline filter is applied. Default is the last
    axis.
output : ndarray or dtype, optional
    The array in which to place the output, or the dtype of the returned
    array. Default is `numpy.float64`.

Returns
-------
spline_filter1d : ndarray or None
    The filtered input. If `output` is given as a parameter, None is
    returned.


def _normalize_sequence(input, rank, array_type=None):

if isinstance(input, integer_types + (float,)):<EOL><INDENT>normalized = [input] * rank<EOL><DEDENT>else:<EOL><INDENT>normalized = list(input)<EOL>if len(normalized) != rank:<EOL><INDENT>err = "<STR_LIT>"<EOL>raise RuntimeError(err)<EOL><DEDENT><DEDENT>return normalized<EOL>

If input is a scalar, create a sequence of length equal to the
    rank by duplicating the input. If input is a sequence,
    check if its length is equal to the length of array.


def grey_opening(input, size=None, footprint=None, structure=None,<EOL>output=None, mode="<STR_LIT>", cval=<NUM_LIT:0.0>, origin=<NUM_LIT:0>):

tmp = grey_erosion(input, size, footprint, structure, None, mode,<EOL>cval, origin)<EOL>return grey_dilation(tmp, size, footprint, structure, output, mode,<EOL>cval, origin)<EOL>

Multi-dimensional greyscale opening.

A greyscale opening consists in the succession of a greyscale erosion,
and a greyscale dilation.

Parameters
----------
input : array_like
    Array over which the grayscale opening is to be computed.
size : tuple of ints
    Shape of a flat and full structuring element used for the grayscale
    opening. Optional if `footprint` or `structure` is provided.
footprint : array of ints, optional
    Positions of non-infinite elements of a flat structuring element
    used for the grayscale opening.
structure : array of ints, optional
    Structuring element used for the grayscale opening. `structure`
    may be a non-flat structuring element.
output : array, optional
    An array used for storing the ouput of the opening may be provided.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
    The `mode` parameter determines how the array borders are
    handled, where `cval` is the value when mode is equal to
    'constant'. Default is 'reflect'
cval : scalar, optional
    Value to fill past edges of input if `mode` is 'constant'. Default
    is 0.0.
origin : scalar, optional
    The `origin` parameter controls the placement of the filter.
    Default 0

Returns
-------
grey_opening : ndarray
    Result of the grayscale opening of `input` with `structure`.

See also
--------
binary_opening, grey_dilation, grey_erosion, grey_closing
generate_binary_structure

Notes
-----
The action of a grayscale opening with a flat structuring element amounts
to smoothen high local maxima, whereas binary opening erases small objects.

References
----------
.. [1] http://en.wikipedia.org/wiki/Mathematical_morphology

Examples
--------
>>> a = np.arange(36).reshape((6,6))
>>> a[3, 3] = 50
>>> a
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 50, 22, 23],
       [24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35]])
>>> ndimage.grey_opening(a, size=(3,3))
array([[ 0,  1,  2,  3,  4,  4],
       [ 6,  7,  8,  9, 10, 10],
       [12, 13, 14, 15, 16, 16],
       [18, 19, 20, 22, 22, 22],
       [24, 25, 26, 27, 28, 28],
       [24, 25, 26, 27, 28, 28]])
>>> # Note that the local maximum a[3,3] has disappeared


if connectivity < <NUM_LIT:1>:<EOL><INDENT>connectivity = <NUM_LIT:1><EOL><DEDENT>if rank < <NUM_LIT:1>:<EOL><INDENT>if connectivity < <NUM_LIT:1>:<EOL><INDENT>return numpy.array(<NUM_LIT:0>, dtype=bool)<EOL><DEDENT>else:<EOL><INDENT>return numpy.array(<NUM_LIT:1>, dtype=bool)<EOL><DEDENT><DEDENT>output = numpy.fabs(numpy.indices([<NUM_LIT:3>] * rank) - <NUM_LIT:1>)<EOL>output = numpy.add.reduce(output, <NUM_LIT:0>)<EOL>return numpy.asarray(output <= connectivity, dtype=bool)<EOL>

Generate a binary structure for binary morphological operations.

Parameters
----------
rank : int
     Number of dimensions of the array to which the structuring element
     will be applied, as returned by `np.ndim`.
connectivity : int
     `connectivity` determines which elements of the output array belong
     to the structure, i.e. are considered as neighbors of the central
     element. Elements up to a squared distance of `connectivity` from
     the center are considered neighbors. `connectivity` may range from 1
     (no diagonal elements are neighbors) to `rank` (all elements are
     neighbors).

Returns
-------
output : ndarray of bools
     Structuring element which may be used for binary morphological
     operations, with `rank` dimensions and all dimensions equal to 3.

See also
--------
iterate_structure, binary_dilation, binary_erosion

Notes
-----
`generate_binary_structure` can only create structuring elements with
dimensions equal to 3, i.e. minimal dimensions. For larger structuring
elements, that are useful e.g. for eroding large objects, one may either
use   `iterate_structure`, or create directly custom arrays with
numpy functions such as `numpy.ones`.

Examples
--------
>>> struct = ndimage.generate_binary_structure(2, 1)
>>> struct
array([[False,  True, False],
       [ True,  True,  True],
       [False,  True, False]], dtype=bool)
>>> a = np.zeros((5,5))
>>> a[2, 2] = 1
>>> a
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype)
>>> b
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype)
array([[ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.]])
>>> struct = ndimage.generate_binary_structure(2, 2)
>>> struct
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
>>> struct = ndimage.generate_binary_structure(3, 1)
>>> struct # no diagonal elements
array([[[False, False, False],
        [False,  True, False],
        [False, False, False]],
       [[False,  True, False],
        [ True,  True,  True],
        [False,  True, False]],
       [[False, False, False],
        [False,  True, False],
        [False, False, False]]], dtype=bool)


_check_obsolete(key)<EOL>return physical_constants[key][<NUM_LIT:2>] / physical_constants[key][<NUM_LIT:0>]<EOL>

Relative precision in physical_constants indexed by key

Parameters
----------
key : Python string or unicode
    Key in dictionary `physical_constants`

Returns
-------
prec : float
    Relative precision in `physical_constants` corresponding to `key`

See Also
--------
codata : Contains the description of `physical_constants`, which, as a
    dictionary literal object, does not itself possess a docstring.

Examples
--------
>>> from scipy.constants import codata
>>> codata.precision(u'proton mass')
4.96226989798e-08


if sub is None:<EOL><INDENT>result = list(_current_constants.keys())<EOL><DEDENT>else:<EOL><INDENT>result = [key for key in _current_constants<EOL>if sub.lower() in key.lower()]<EOL><DEDENT>result.sort()<EOL>if disp:<EOL><INDENT>for key in result:<EOL><INDENT>print(key)<EOL><DEDENT>return<EOL><DEDENT>else:<EOL><INDENT>return result<EOL><DEDENT>

Return list of codata.physical_constant keys containing a given string.

Parameters
----------
sub : str, unicode
    Sub-string to search keys for.  By default, return all keys.
disp : bool
    If True, print the keys that are found, and return None.
    Otherwise, return the list of keys without printing anything.

Returns
-------
keys : list or None
    If `disp` is False, the list of keys is returned.
    Otherwise, None is returned.

See Also
--------
codata : Contains the description of `physical_constants`, which, as a
    dictionary literal object, does not itself possess a docstring.


with _ellip_lock:<EOL><INDENT>with np.errstate(all='<STR_LIT:ignore>'):<EOL><INDENT>return _ellip_harm_2_vec(h2, k2, n, p, s)<EOL><DEDENT><DEDENT>

r"""
    Ellipsoidal harmonic functions F^p_n(l)

    These are also known as Lame functions of the second kind, and are
    solutions to the Lame equation:

    .. math:: (s^2 - h^2)(s^2 - k^2)F''(s) + s(2s^2 - h^2 - k^2)F'(s) + (a - q s^2)F(s) = 0

    where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
    returned) corresponding to the solutions.

    Parameters
    ----------
    h2 : float
        ``h**2``
    k2 : float
        ``k**2``; should be larger than ``h**2``
    n : int
        Degree.
    p : int
        Order, can range between [1,2n+1].
    s : float
        Coordinate

    Returns
    -------
    F : float
        The harmonic :math:`F^p_n(s)`

    Notes
    -----
    Lame functions of the second kind are related to the functions of the first kind:

    .. math::

       F^p_n(s)=(2n + 1)E^p_n(s)\int_{0}^{1/s}\frac{du}{(E^p_n(1/u))^2\sqrt{(1-u^2k^2)(1-u^2h^2)}}

    See Also
    --------
    ellip_harm, ellip_normal

    Examples
    --------
    >>> from scipy.special import ellip_harm_2
    >>> w = ellip_harm_2(5,8,2,1,10)
    >>> w
    0.00108056853382


def ellip_harm(h2, k2, n, p, s, signm=<NUM_LIT:1>, signn=<NUM_LIT:1>):

return _ellip_harm(h2, k2, n, p, s, signm, signn)<EOL>

r"""
    Ellipsoidal harmonic functions E^p_n(l)

    These are also known as Lame functions of the first kind, and are
    solutions to the Lame equation:

    .. math:: (s^2 - h^2)(s^2 - k^2)E''(s) + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0

    where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
    returned) corresponding to the solutions.

    Parameters
    ----------
    h2 : float
        ``h**2``
    k2 : float
        ``k**2``; should be larger than ``h**2``
    n : int
        Degree
    s : float
        Coordinate
    p : int
        Order, can range between [1,2n+1]
    signm : {1, -1}, optional
        Sign of prefactor of functions. Can be +/-1. See Notes.
    signn : {1, -1}, optional
        Sign of prefactor of functions. Can be +/-1. See Notes.

    Returns
    -------
    E : float
        the harmonic :math:`E^p_n(s)`

    See Also
    --------
    ellip_harm_2, ellip_normal

    Notes
    -----
    The geometric intepretation of the ellipsoidal functions is
    explained in [2]_, [3]_, [4]_.  The `signm` and `signn` arguments control the
    sign of prefactors for functions according to their type::

        K : +1
        L : signm
        M : signn
        N : signm*signn

    References
    ----------
    .. [1] Digital Libary of Mathematical Functions 29.12
       http://dlmf.nist.gov/29.12
    .. [2] Bardhan and Knepley, "Computational science and
       re-discovery: open-source implementations of
       ellipsoidal harmonics for problems in potential theory",
       Comput. Sci. Disc. 5, 014006 (2012)
       doi:10.1088/1749-4699/5/1/014006
    .. [3] David J.and Dechambre P, "Computation of Ellipsoidal
       Gravity Field Harmonics for small solar system bodies"
       pp. 30-36, 2000
    .. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications"
       pp. 418, 2012

    Examples
    --------
    >>> from scipy.special import ellip_harm
    >>> w = ellip_harm(5,8,1,1,2.5)
    >>> w
    2.5

    Check that the functions indeed are solutions to the Lame equation:

    >>> from scipy.interpolate import UnivariateSpline
    >>> def eigenvalue(f, df, ddf):
    ...     r = ((s**2 - h**2)*(s**2 - k**2)*ddf + s*(2*s**2 - h**2 - k**2)*df - n*(n+1)*s**2*f)/f
    ...     return -r.mean(), r.std()
    >>> s = np.linspace(0.1, 10, 200)
    >>> k, h, n, p = 8.0, 2.2, 3, 2
    >>> E = ellip_harm(h**2, k**2, n, p, s)
    >>> E_spl = UnivariateSpline(s, E)
    >>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2))
    >>> a, a_err
    (583.44366156701483, 6.4580890640310646e-11)


if np.any(list(map(np.iscomplexobj, self.param_columns))):<EOL><INDENT>is_complex = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>is_complex = "<STR_LIT>"<EOL><DEDENT>if self.dataname:<EOL><INDENT>return "<STR_LIT>" % (self.func.__name__, is_complex,<EOL>os.path.basename(self.dataname))<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>" % (self.func.__name__, is_complex)<EOL><DEDENT>


def wrap(*a, **kw):<EOL><INDENT>try:<EOL><INDENT>return func(*a, **kw)<EOL><DEDENT>except Exception:<EOL><INDENT>return np.nan<EOL><DEDENT><DEDENT>return wrap<EOL>

Decorate function to return nan if it raises an exception


<EOL>for v in [-<NUM_LIT>, -<NUM_LIT>, -<NUM_LIT>, -<NUM_LIT>, -<NUM_LIT:1.>, -<NUM_LIT>,<EOL><NUM_LIT:0.>, <NUM_LIT:1.>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>]:<EOL><INDENT>for z in [-<NUM_LIT>, -<NUM_LIT:11>, -<NUM_LIT:10>, -<NUM_LIT:1>, <NUM_LIT:1.>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>]:<EOL><INDENT>yield v, z<EOL><DEDENT><DEDENT>for v in <NUM_LIT:0.5> + arange(-<NUM_LIT>, <NUM_LIT>):<EOL><INDENT>yield v, <NUM_LIT><EOL><DEDENT>

Yield points at which to compare Cephes implementation to AMOS


return ellipkm1(<NUM_LIT:1> - asarray(m))<EOL>

Complete elliptic integral of the first kind

This function is defined as

.. math:: K(m) = \\int_0^{\\pi/2} [1 - m \\sin(t)^2]^{-1/2} dt

Parameters
----------
m : array_like
    The parameter of the elliptic integral.

Returns
-------
K : array_like
    Value of the elliptic integral.

Notes
-----
For more precision around point m = 1, use `ellipkm1`.

See Also
--------
ellipkm1 : Complete elliptic integral of the first kind around m = 1
ellipkinc : Incomplete elliptic integral of the first kind
ellipe : Complete elliptic integral of the second kind
ellipeinc : Incomplete elliptic integral of the second kind


if (floor(nt) != nt) or (nt <= <NUM_LIT:0>) or not isscalar(nt):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return specfun.cerzo(nt)<EOL>

Compute nt complex zeros of the error function erf(z).


if not (isscalar(v) and isscalar(x)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>n = int(v)<EOL>v0 = v-n<EOL>if (n < <NUM_LIT:1>):<EOL><INDENT>n1 = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>n1 = n<EOL><DEDENT>v1 = n1 + v0<EOL>dv,dp,pdf,pdd = specfun.pbdv(v1,x)<EOL>return dv[:n1+<NUM_LIT:1>],dp[:n1+<NUM_LIT:1>]<EOL>

Compute sequence of parabolic cylinder functions Dv(x) and
    their derivatives for Dv0(x)..Dv(x) with v0=v-int(v).


return jnyn_zeros(n,nt)[<NUM_LIT:3>]<EOL>

Compute nt zeros of the Bessel function Yn'(x).


if not isscalar(nt) or (floor(nt) != nt) or (nt <= <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return specfun.klvnzo(nt,<NUM_LIT:2>)<EOL>

Compute nt zeros of the Kelvin function bei x


if not (isscalar(n) and isscalar(z)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n != floor(n)) or (n < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n < <NUM_LIT:1>):<EOL><INDENT>n1 = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>n1 = n<EOL><DEDENT>if iscomplex(z):<EOL><INDENT>nm,jn,jnp,yn,ynp = specfun.csphjy(n1,z)<EOL><DEDENT>else:<EOL><INDENT>nm,jn,jnp = specfun.sphj(n1,z)<EOL><DEDENT>return jn[:(n+<NUM_LIT:1>)], jnp[:(n+<NUM_LIT:1>)]<EOL>

Compute the spherical Bessel function jn(z) and its derivative for
    all orders up to and including n.


if not isinstance(n,int) or (n < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if n == <NUM_LIT:0>:<EOL><INDENT>return hankel1(v,z)<EOL><DEDENT>else:<EOL><INDENT>return _bessel_diff_formula(v, z, n, hankel1, -<NUM_LIT:1>)<EOL><DEDENT>

Return the nth derivative of H1v(z) with respect to z.


if not (isscalar(m) and isscalar(n) and isscalar(c)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n != floor(n)) or (m != floor(m)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n-m > <NUM_LIT>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>maxL = n-m+<NUM_LIT:1><EOL>return specfun.segv(m,n,c,<NUM_LIT:1>)[<NUM_LIT:1>][:maxL]<EOL>

Compute a sequence of characteristic values for the prolate
    spheroidal wave functions for mode m and n'=m..n and spheroidal
    parameter c.


if not (isscalar(n) and isscalar(z)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n != floor(n)) or (n < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n < <NUM_LIT:1>):<EOL><INDENT>n1 = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>n1 = n<EOL><DEDENT>if iscomplex(z) or less(z,<NUM_LIT:0>):<EOL><INDENT>nm,In,Inp,kn,knp = specfun.csphik(n1,z)<EOL><DEDENT>else:<EOL><INDENT>nm,kn,knp = specfun.sphk(n1,z)<EOL><DEDENT>return kn[:(n+<NUM_LIT:1>)], knp[:(n+<NUM_LIT:1>)]<EOL>

Compute the spherical Bessel function kn(z) and its derivative for
    all orders up to and including n.


if not (isscalar(n) and isscalar(x)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n != floor(n)) or (n < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n == <NUM_LIT:0>):<EOL><INDENT>n1 = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>n1 = n<EOL><DEDENT>nm,jn,jnp = specfun.rctj(n1,x)<EOL>return jn[:(n+<NUM_LIT:1>)],jnp[:(n+<NUM_LIT:1>)]<EOL>

Compute the Ricatti-Bessel function of the first kind and its
    derivative for all orders up to and including n.


if not isscalar(m) or (abs(m) > n):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not isscalar(n) or (n < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not isscalar(z):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not(type == <NUM_LIT:2> or type == <NUM_LIT:3>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (m < <NUM_LIT:0>):<EOL><INDENT>mp = -m<EOL>mf,nf = mgrid[<NUM_LIT:0>:mp+<NUM_LIT:1>,<NUM_LIT:0>:n+<NUM_LIT:1>]<EOL>sv = errprint(<NUM_LIT:0>)<EOL>if type == <NUM_LIT:2>:<EOL><INDENT>fixarr = where(mf > nf,<NUM_LIT:0.0>, (-<NUM_LIT:1>)**mf * gamma(nf-mf+<NUM_LIT:1>) / gamma(nf+mf+<NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>fixarr = where(mf > nf,<NUM_LIT:0.0>,gamma(nf-mf+<NUM_LIT:1>) / gamma(nf+mf+<NUM_LIT:1>))<EOL><DEDENT>sv = errprint(sv)<EOL><DEDENT>else:<EOL><INDENT>mp = m<EOL><DEDENT>p,pd = specfun.clpmn(mp,n,real(z),imag(z),type)<EOL>if (m < <NUM_LIT:0>):<EOL><INDENT>p = p * fixarr<EOL>pd = pd * fixarr<EOL><DEDENT>return p,pd<EOL>

Associated Legendre function of the first kind, Pmn(z)

    Computes the (associated) Legendre function of the first kind
    of order m and degree n,::

        Pmn(z) = P_n^m(z)

    and its derivative, ``Pmn'(z)``.  Returns two arrays of size
    ``(m+1, n+1)`` containing ``Pmn(z)`` and ``Pmn'(z)`` for all
    orders from ``0..m`` and degrees from ``0..n``.

    Parameters
    ----------
    m : int
       ``|m| <= n``; the order of the Legendre function.
    n : int
       where ``n >= 0``; the degree of the Legendre function.  Often
       called ``l`` (lower case L) in descriptions of the associated
       Legendre function
    z : float or complex
        Input value.
    type : int
       takes values 2 or 3
       2: cut on the real axis |x|>1
       3: cut on the real axis -1<x<1 (default)

    Returns
    -------
    Pmn_z : (m+1, n+1) array
       Values for all orders 0..m and degrees 0..n
    Pmn_d_z : (m+1, n+1) array
       Derivatives for all orders 0..m and degrees 0..n

    See Also
    --------
    lpmn: associated Legendre functions of the first kind for real z

    Notes
    -----
    By default, i.e. for ``type=3``, phase conventions are chosen according
    to [1]_ such that the function is analytic. The cut lies on the interval
    (-1, 1). Approaching the cut from above or below in general yields a phase
    factor with respect to Ferrer's function of the first kind
    (cf. `lpmn`).

    For ``type=2`` a cut at |x|>1 is chosen. Approaching the real values
    on the interval (-1, 1) in the complex plane yields Ferrer's function
    of the first kind.

    References
    ----------
    .. [1] NIST Digital Library of Mathematical Functions
           http://dlmf.nist.gov/14.21


if not (isscalar(n) and isscalar(z)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n != floor(n)) or (n < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n < <NUM_LIT:1>):<EOL><INDENT>n1 = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>n1 = n<EOL><DEDENT>if iscomplex(z):<EOL><INDENT>qn,qd = specfun.clqn(n1,z)<EOL><DEDENT>else:<EOL><INDENT>qn,qd = specfun.lqnb(n1,z)<EOL><DEDENT>return qn[:(n+<NUM_LIT:1>)],qd[:(n+<NUM_LIT:1>)]<EOL>

Compute sequence of Legendre functions of the second kind,
    Qn(z) and derivatives for all degrees from 0 to n (inclusive).


def comb(N, k, exact=False, repetition=False):

if repetition:<EOL><INDENT>return comb(N + k - <NUM_LIT:1>, k, exact)<EOL><DEDENT>if exact:<EOL><INDENT>N = int(N)<EOL>k = int(k)<EOL>if (k > N) or (N < <NUM_LIT:0>) or (k < <NUM_LIT:0>):<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>val = <NUM_LIT:1><EOL>for j in xrange(min(k, N-k)):<EOL><INDENT>val = (val*(N-j))//(j+<NUM_LIT:1>)<EOL><DEDENT>return val<EOL><DEDENT>else:<EOL><INDENT>k,N = asarray(k), asarray(N)<EOL>cond = (k <= N) & (N >= <NUM_LIT:0>) & (k >= <NUM_LIT:0>)<EOL>vals = binom(N, k)<EOL>if isinstance(vals, np.ndarray):<EOL><INDENT>vals[~cond] = <NUM_LIT:0><EOL><DEDENT>elif not cond:<EOL><INDENT>vals = np.float64(<NUM_LIT:0>)<EOL><DEDENT>return vals<EOL><DEDENT>

The number of combinations of N things taken k at a time.

This is often expressed as "N choose k".

Parameters
----------
N : int, ndarray
    Number of things.
k : int, ndarray
    Number of elements taken.
exact : bool, optional
    If `exact` is False, then floating point precision is used, otherwise
    exact long integer is computed.
repetition : bool, optional
    If `repetition` is True, then the number of combinations with
    repetition is computed.

Returns
-------
val : int, ndarray
    The total number of combinations.

Notes
-----
- Array arguments accepted only for exact=False case.
- If k > N, N < 0, or k < 0, then a 0 is returned.

Examples
--------
>>> k = np.array([3, 4])
>>> n = np.array([10, 10])
>>> sc.comb(n, k, exact=False)
array([ 120.,  210.])
>>> sc.comb(10, 3, exact=True)
120L
>>> sc.comb(10, 3, exact=True, repetition=True)
220L


if exact:<EOL><INDENT>if n < <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>val = <NUM_LIT:1><EOL>for k in xrange(<NUM_LIT:1>,n+<NUM_LIT:1>):<EOL><INDENT>val *= k<EOL><DEDENT>return val<EOL><DEDENT>else:<EOL><INDENT>n = asarray(n)<EOL>vals = gamma(n+<NUM_LIT:1>)<EOL>return where(n >= <NUM_LIT:0>,vals,<NUM_LIT:0>)<EOL><DEDENT>

The factorial function, n! = special.gamma(n+1).

If exact is 0, then floating point precision is used, otherwise
exact long integer is computed.

- Array argument accepted only for exact=False case.
- If n<0, the return value is 0.

Parameters
----------
n : int or array_like of ints
    Calculate ``n!``.  Arrays are only supported with `exact` set
    to False.  If ``n < 0``, the return value is 0.
exact : bool, optional
    The result can be approximated rapidly using the gamma-formula
    above.  If `exact` is set to True, calculate the
    answer exactly using integer arithmetic. Default is False.

Returns
-------
nf : float or int
    Factorial of `n`, as an integer or a float depending on `exact`.

Examples
--------
>>> arr = np.array([3,4,5])
>>> sc.factorial(arr, exact=False)
array([   6.,   24.,  120.])
>>> sc.factorial(5, exact=True)
120L


if not isscalar(m) or (m < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not isscalar(n) or (n < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not isscalar(z):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>m = int(m)<EOL>n = int(n)<EOL>mm = max(<NUM_LIT:1>,m)<EOL>nn = max(<NUM_LIT:1>,n)<EOL>if iscomplex(z):<EOL><INDENT>q,qd = specfun.clqmn(mm,nn,z)<EOL><DEDENT>else:<EOL><INDENT>q,qd = specfun.lqmn(mm,nn,z)<EOL><DEDENT>return q[:(m+<NUM_LIT:1>),:(n+<NUM_LIT:1>)],qd[:(m+<NUM_LIT:1>),:(n+<NUM_LIT:1>)]<EOL>

Associated Legendre functions of the second kind, Qmn(z) and its
    derivative, ``Qmn'(z)`` of order m and degree n.  Returns two
    arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and ``Qmn'(z)`` for
    all orders from ``0..m`` and degrees from ``0..n``.

    z can be complex.


if not isscalar(nt) or (floor(nt) != nt) or (nt <= <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return specfun.klvnzo(nt,<NUM_LIT:6>)<EOL>

Compute nt zeros of the Kelvin function bei' x


if not isscalar(nt) or (floor(nt) != nt) or (nt > <NUM_LIT>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>nt = int(nt)<EOL>n,m,t,zo = specfun.jdzo(nt)<EOL>return zo[<NUM_LIT:1>:nt+<NUM_LIT:1>],n[:nt],m[:nt],t[:nt]<EOL>

Compute nt (<=1200) zeros of the Bessel functions Jn and Jn'
    and arange them in order of their magnitudes.

    Returns
    -------
    zo[l-1] : ndarray
        Value of the lth zero of Jn(x) and Jn'(x). Of length `nt`.
    n[l-1] : ndarray
        Order of the Jn(x) or Jn'(x) associated with lth zero. Of length `nt`.
    m[l-1] : ndarray
        Serial number of the zeros of Jn(x) or Jn'(x) associated
        with lth zero. Of length `nt`.
    t[l-1] : ndarray
        0 if lth zero in zo is zero of Jn(x), 1 if it is a zero of Jn'(x). Of
        length `nt`.

    See Also
    --------
    jn_zeros, jnp_zeros : to get separated arrays of zeros.


if not (isscalar(m) and isscalar(n) and isscalar(c)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n != floor(n)) or (m != floor(m)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n-m > <NUM_LIT>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>maxL = n-m+<NUM_LIT:1><EOL>return specfun.segv(m,n,c,-<NUM_LIT:1>)[<NUM_LIT:1>][:maxL]<EOL>

Compute a sequence of characteristic values for the oblate
    spheroidal wave functions for mode m and n'=m..n and spheroidal
    parameter c.


if not isscalar(nt) or (floor(nt) != nt) or (nt <= <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>kf = <NUM_LIT:0><EOL>kc = (complex != <NUM_LIT:1>)<EOL>return specfun.cyzo(nt,kf,kc)<EOL>

Returns nt (complex or real) zeros of Y0(z), z0, and the value
    of Y0'(z0) = -Y1(z0) at each zero.


return jnyn_zeros(n,nt)[<NUM_LIT:0>]<EOL>

Compute nt zeros of the Bessel function Jn(x).


if n < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if n == <NUM_LIT:0>:<EOL><INDENT>n1 = n + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>n1 = n<EOL><DEDENT>x, w, mu0 = c_roots(n1, mu=True)<EOL>if n == <NUM_LIT:0>:<EOL><INDENT>x, w = [], []<EOL><DEDENT>hn = <NUM_LIT:4> * pi * ((n == <NUM_LIT:0>) + <NUM_LIT:1>)<EOL>kn = <NUM_LIT:1.0><EOL>p = orthopoly1d(x, w, hn, kn,<EOL>wfunc=lambda x: <NUM_LIT:1.0> / sqrt(<NUM_LIT:1> - x * x / <NUM_LIT>),<EOL>limits=(-<NUM_LIT:2>, <NUM_LIT:2>), monic=monic)<EOL>if not monic:<EOL><INDENT>p._scale(<NUM_LIT> / p(<NUM_LIT:2>))<EOL>p.__dict__['<STR_LIT>'] = lambda x: eval_chebyc(n, x)<EOL><DEDENT>return p<EOL>

Return nth order Chebyshev polynomial of first kind, Cn(x).  Orthogonal
    over [-2,2] with weight function (1-(x/2)**2)**(-1/2).


base = jacobi(n, <NUM_LIT:0.5>, <NUM_LIT:0.5>, monic=monic)<EOL>if monic:<EOL><INDENT>return base<EOL><DEDENT>factor = sqrt(pi) / <NUM_LIT> * _gam(n + <NUM_LIT:2>) / _gam(n + <NUM_LIT>)<EOL>base._scale(factor)<EOL>return base<EOL>

Return nth order Chebyshev polynomial of second kind, Un(x).  Orthogonal
    over [-1,1] with weight function (1-x**2)**(1/2).