
    ^Mh@                       g d Z dZddlZddlZddlZddlZddlmZmZm	Z	m
Z
mZmZ ddlZddlmZmZmZ ddlmZ ddlmZmZmZmZ dd	lmZ dd
lmZ ddlmZmZm Z m!Z!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddl(m)Z* dddddddZ+ G d d          Z,dfdZ- G d de           Z. G d de/          Z0d Z1d Z2d Z3 e ej4        e5          j6                  Z7dgd!Z8	 	 	 dhd#Z9d$ Z:d% Z;d& Z<d' Z=d( Z>d) Z?d* Z@ G d+ d,eA          ZBd- ZC	 	 did/ZD	 	 	 	 djd1ZEe7fd2ZF e"d3d45          e7d6dd7d8            ZGd9 ZH G d: d;eA          ZId< ZJdd"d=ejK        e7ddddddd.d>dfd?ZLd"ddd=ejK        e7dd0d0ddd.d>dfd@ZMdfdAZNdd"d=ejK        e7dddddd.dBfdCZOd"ddd=ejK        e7dd0d0dd.dBfdDZPddd"d=e7dddddd.d>fdEZQd"ddddd=e7dd0d0d.d>fdFZR	 	 dkdHZS	 	 dldIZT G dJ dK          ZUdmdMZV	 	 dndNZWd"de7ddOfdPZXdd"e7dOdfdQZYdodVZZ G dW dXeA          Z[dY Z\dZ Z]	 	 dpd\Z^	 	 	 did]Z_	 	 	 dqd^Z`d_ Zad"d`deDd0dfdaZb G db dc          ZcdrdeZddS )s)fminfmin_powell	fmin_bfgsfmin_ncgfmin_cg	fminboundbrentgoldenbracketrosen	rosen_der
rosen_hessrosen_hess_prodbruteapprox_fprimeline_search
check_gradOptimizeResultshow_optionsOptimizeWarningzrestructuredtext en    N)eyeargminzerosshapeasarraysqrt)choleskyissymmetricLinAlgError)LinearOperator   )line_search_wolfe1line_search_wolfe2r#   LineSearchWarning)approx_derivative)getfullargspec_no_self)
MapWrappercheck_random_state_RichResult_call_callback_maybe_halt_transition_to_rng)ScalarFunction
FD_METHODS)array_namespace)array_api_extraz%Optimization terminated successfully.z9Maximum number of function evaluations has been exceeded.z/Maximum number of iterations has been exceeded.z=Desired error not necessarily achieved due to precision loss.zNaN result encountered.z-The result is outside of the provided bounds.)successmaxfevmaxiterpr_lossnanout_of_boundsc                   *    e Zd ZdZd Zd Zd Zd ZdS )
MemoizeJaczkDecorator that caches the return values of a function returning ``(fun, grad)``
    each time it is called.c                 >    || _         d | _        d | _        d | _        d S N)funjac_valuex)selfr:   s     X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_optimize.py__init__zMemoizeJac.__init__A   s"        c                    t          j        || j        k              r| j        | j        Ut          j        |                                          | _         | j        |g|R  }|d         | _        |d         | _        d S d S )Nr!   r   )npallr=   r<   r;   r   copyr:   )r>   r=   argsfgs       r?   _compute_if_neededzMemoizeJac._compute_if_neededG   s    va46k"" 	 dk&9TX=MZ]]''))DF!#d###B!uDHQ%DKKK	 >N=MrA   c                 ,     | j         |g|R   | j        S )z returns the function value )rH   r<   r>   r=   rF   s      r?   __call__zMemoizeJac.__call__N   s%    )D)))){rA   c                 ,     | j         |g|R   | j        S r9   )rH   r;   rJ   s      r?   
derivativezMemoizeJac.derivativeS   s$    )D))))xrA   N)__name__
__module____qualname____doc__r@   rH   rK   rM    rA   r?   r7   r7   =   sZ                  
    rA   r7   c                       |dv r S t          j                   }t          |j                  dhk    r fd}n|dk    r fd}n|dk    r fd}n fd	}d
|_        |S )zAWrap a user-provided callback so that attributes can be attached.N>   tncslsqpcobylacobyqaintermediate_resultc                      |           S )N)rX   rR   rescallbacks    r?   wrapped_callbackz(_wrap_callback.<locals>.wrapped_callback`   s    84444rA   trust-constrc                 J     t          j        | j                  |           S r9   rC   rE   r=   rZ   s    r?   r]   z(_wrap_callback.<locals>.wrapped_callbackc   s    8BGCENNC000rA   differential_evolutionc                 T     t          j        | j                  | j                  S r9   )rC   rE   r=   convergencerZ   s    r?   r]   z(_wrap_callback.<locals>.wrapped_callbackf   s!    8BGCENNCO<<<rA   c                 H     t          j        | j                            S r9   r`   rZ   s    r?   r]   z(_wrap_callback.<locals>.wrapped_callbacki   s    8BGCENN+++rA   F)inspect	signatureset
parametersstop_iteration)r\   methodsigr]   s   `   r?   _wrap_callbackrl   X   s    6%III

H
%
%C
3>4555	5 	5 	5 	5 	5 	5	>	!	!	1 	1 	1 	1 	1 	1	+	+	+	= 	= 	= 	= 	= 	=	, 	, 	, 	, 	, ',#rA   c                       e Zd ZdZdS )r   a  
    Represents the optimization result.

    Attributes
    ----------
    x : ndarray
        The solution of the optimization.
    success : bool
        Whether or not the optimizer exited successfully.
    status : int
        Termination status of the optimizer. Its value depends on the
        underlying solver. Refer to `message` for details.
    message : str
        Description of the cause of the termination.
    fun : float
        Value of objective function at `x`.
    jac, hess : ndarray
        Values of objective function's Jacobian and its Hessian at `x` (if
        available). The Hessian may be an approximation, see the documentation
        of the function in question.
    hess_inv : object
        Inverse of the objective function's Hessian; may be an approximation.
        Not available for all solvers. The type of this attribute may be
        either np.ndarray or scipy.sparse.linalg.LinearOperator.
    nfev, njev, nhev : int
        Number of evaluations of the objective functions and of its
        Jacobian and Hessian.
    nit : int
        Number of iterations performed by the optimizer.
    maxcv : float
        The maximum constraint violation.

    Notes
    -----
    Depending on the specific solver being used, `OptimizeResult` may
    not have all attributes listed here, and they may have additional
    attributes not listed here. Since this class is essentially a
    subclass of dict with attribute accessors, one can see which
    attributes are available using the `OptimizeResult.keys` method.

    N)rN   rO   rP   rQ   rR   rA   r?   r   r   p   s        ( (R 	DrA   r   c                       e Zd ZdS )r   NrN   rO   rP   rR   rA   r?   r   r              DrA   r   c                 H    d }|  ||           st          d          d S d S )Nc                 j    t          |           r#	 t          |            dS # t          $ r Y dS w xY wdS )NTF)r   r   r   )As    r?   
is_pos_defz,_check_positive_definite.<locals>.is_pos_def   sN    q>> 	t   uu 5s   " 
00z+'hess_inv0' matrix isn't positive definite.)
ValueError)Hkrt   s     r?   _check_positive_definiterw      sK       
~z"~~ 	LJKKK ~	L 	LrA   c                     | r[d                     t          t          |                                                     }t	          j        d| t          d           d S d S )Nz, zUnknown solver options:    
stacklevel)joinmapstrkeyswarningswarnr   )unknown_optionsmsgs     r?   _check_unknown_optionsr      sg     WiiC!5!5!7!78899 	666TUVVVVVVW WrA   c                 Z    t          j        |           dk    ot          j        |           S )zJTest whether `x` is either a finite scalar or a finite array scalar.

    r!   )rC   sizeisfinite)r=   s    r?   is_finite_scalarr      s#     71::?-r{1~~-rA      c                 >   |t           j        k    r&t          j        t          j        |                     S |t           j         k    r&t          j        t          j        |                     S t          j        t          j        |           |z  d          d|z  z  S )Nr   axis      ?)rC   infamaxabsaminsum)r=   ords     r?   vecnormr      st    
bf}}wrvayy!!!	wrvayy!!!vbfQiin1---c	::rA   rR   c           
          t          |          r|}n|t          v rd}|}nd}|}|d }|t          j         t          j        f}t	          | |||||||          }	|	S )a	  
    Creates a ScalarFunction object for use with scalar minimizers
    (BFGS/LBFGSB/SLSQP/TNC/CG/etc).

    Parameters
    ----------
    fun : callable
        The objective function to be minimized.

            ``fun(x, *args) -> float``

        where ``x`` is an 1-D array with shape (n,) and ``args``
        is a tuple of the fixed parameters needed to completely
        specify the function.
    x0 : ndarray, shape (n,)
        Initial guess. Array of real elements of size (n,),
        where 'n' is the number of independent variables.
    jac : {callable,  '2-point', '3-point', 'cs', None}, optional
        Method for computing the gradient vector. If it is a callable, it
        should be a function that returns the gradient vector:

            ``jac(x, *args) -> array_like, shape (n,)``

        If one of `{'2-point', '3-point', 'cs'}` is selected then the gradient
        is calculated with a relative step for finite differences. If `None`,
        then two-point finite differences with an absolute step is used.
    args : tuple, optional
        Extra arguments passed to the objective function and its
        derivatives (`fun`, `jac` functions).
    bounds : sequence, optional
        Bounds on variables. 'new-style' bounds are required.
    eps : float or ndarray
        If ``jac is None`` the absolute step size used for numerical
        approximation of the jacobian via forward differences.
    finite_diff_rel_step : None or array_like, optional
        If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
        use for numerical approximation of the jacobian. The absolute step
        size is computed as ``h = rel_step * sign(x0) * max(1, abs(x0))``,
        possibly adjusted to fit into the bounds. For ``jac='3-point'``
        the sign of `h` is ignored. If None (default) then step is selected
        automatically.
    hess : {callable,  '2-point', '3-point', 'cs', None}
        Computes the Hessian matrix. If it is callable, it should return the
        Hessian matrix:

            ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)``

        Alternatively, the keywords {'2-point', '3-point', 'cs'} select a
        finite difference scheme for numerical estimation.
        Whenever the gradient is estimated via finite-differences, the Hessian
        cannot be estimated with options {'2-point', '3-point', 'cs'} and needs
        to be estimated using one of the quasi-Newton strategies.

    Returns
    -------
    sf : ScalarFunction
    N2-pointc                     d S r9   rR   )r=   rF   s     r?   hessz&_prepare_scalar_function.<locals>.hess  s    4rA   )epsilon)callabler-   rC   r   r,   )
r:   x0r;   rF   boundsr   finite_diff_rel_stepr   gradsfs
             r?   _prepare_scalar_functionr      s    x }} 	
		  |
	 	 	 ~6'26" 
RtT,fg
G 
G 
GB IrA   c                       fd}|S )Nc                 :    t          |           }  |           S r9   )_check_clip_x)r=   r   funcs    r?   evalz_clip_x_for_func.<locals>.eval/  s    !V$$tAwwrA   rR   )r   r   r   s   `` r?   _clip_x_for_funcr   )  s)          KrA   c                     | |d         k                                      s| |d         k                                     r@t          j        dt          d           t	          j        | |d         |d                   } | S | S )Nr   r!   zJValues in x were outside bounds during a minimize step, clipping to bounds   rz   )anyr   r   RuntimeWarningrC   clip)r=   r   s     r?   r   r   6  s    	F1I VAY 3 3 5 5  :$	4 	4 	4 	4 GAvay&),,HrA   c                 t   t          |           }|                    |           } |                    | j        d          r.|                    | |                    d          j                  } |                    d| dd         | dd         dz  z
  dz  z  d| dd         z
  dz  z   d| j        	          }|S )
a  
    The Rosenbrock function.

    The function computed is::

        sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)

    Parameters
    ----------
    x : array_like
        1-D array of points at which the Rosenbrock function is to be computed.

    Returns
    -------
    f : float
        The value of the Rosenbrock function.

    See Also
    --------
    rosen_der, rosen_hess, rosen_hess_prod

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.optimize import rosen
    >>> X = 0.1 * np.arange(10)
    >>> rosen(X)
    76.56

    For higher-dimensional input ``rosen`` broadcasts.
    In the following example, we use this to plot a 2D landscape.
    Note that ``rosen_hess`` does not broadcast in this manner.

    >>> import matplotlib.pyplot as plt
    >>> from mpl_toolkits.mplot3d import Axes3D
    >>> x = np.linspace(-1, 1, 50)
    >>> X, Y = np.meshgrid(x, x)
    >>> ax = plt.subplot(111, projection='3d')
    >>> ax.plot_surface(X, Y, rosen([X, Y]))
    >>> plt.show()
    integralr   g      Y@r!   N       @r   )r   dtype)r.   r   isdtyper   astyper   )r=   xprs      r?   r   r   A  s    T 
		B


1A	zz!':&& /IIaB-..
u!""#2#+c11Q3B3Z#4EEQW 	 	& 	&AHrA   c                 .   t          |           }|                    |           } |                    | j        d          r.|                    | |                    d          j                  } | dd         }| dd         }| dd         }|                    |           }d||dz  z
  z  d	||dz  z
  z  |z  z
  dd|z
  z  z
  |dd<   d
| d         z  | d         | d         dz  z
  z  dd| d         z
  z  z
  |d<   d| d         | d         dz  z
  z  |d<   |S )aP  
    The derivative (i.e. gradient) of the Rosenbrock function.

    Parameters
    ----------
    x : array_like
        1-D array of points at which the derivative is to be computed.

    Returns
    -------
    rosen_der : (N,) ndarray
        The gradient of the Rosenbrock function at `x`.

    See Also
    --------
    rosen, rosen_hess, rosen_hess_prod

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.optimize import rosen_der
    >>> X = 0.1 * np.arange(9)
    >>> rosen_der(X)
    array([ -2. ,  10.6,  15.6,  13.4,   6.4,  -3. , -12.4, -19.4,  62. ])

    r   r   r!   r   Nr        pr   )r.   r   r   r   r   
zeros_like)r=   r   xmxm_m1xm_p1ders         r?   r   r   t  s/   6 
		B


1A	zz!':&& /IIaB-..	
1R4BcrcFEabbEE
--

CUAX&A&+,./1r6l;C"IAaD[AaD1Q47N+a1qt8n<CFQrUQrUAX%&CGJrA   c                    t          |           }t          j        | d|          } |                    | j        d          r.|                    | |                    d          j                  } t          j        d| dd         z  d|          t          j        d	| dd         z  d|          z
  }|                    | j	        d
         | j                  }d| d
         dz  z  d	| d         z  z
  dz   |d
<   d|d<   dd| dd         dz  z  z   d	| dd         z  z
  |dd<   |t          j        ||          z   S )a  
    The Hessian matrix of the Rosenbrock function.

    Parameters
    ----------
    x : array_like
        1-D array of points at which the Hessian matrix is to be computed.

    Returns
    -------
    rosen_hess : ndarray
        The Hessian matrix of the Rosenbrock function at `x`.

    See Also
    --------
    rosen, rosen_der, rosen_hess_prod

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.optimize import rosen_hess
    >>> X = 0.1 * np.arange(4)
    >>> rosen_hess(X)
    array([[-38.,   0.,   0.,   0.],
           [  0., 134., -40.,   0.],
           [  0., -40., 130., -80.],
           [  0.,   0., -80., 200.]])

    r!   ndimr   r   r   r   Nr   )offsetr   r   r   r     r   r      )r   )
r.   xpx
atleast_ndr   r   r   r   create_diagonalr   r   )r=   r   Hdiagonals       r?   r   r     sD   < 
		BqqR(((A	zz!':&& /IIaB-..		TAcrcF]1	<	<	<sQssV|B2>>>
?Axx
!'x22H1q.31:-1HQKHRL4!AbD'1*,,sQqrrU{:HQrTNs"833333rA   c                    t          | |          }t          j        | d|          } |                    | j        d          r.|                    | |                    d          j                  } |                    || j                  }|                    | j        d         | j                  }d| d         dz  z  d	| d         z  z
  dz   |d         z  d	| d         z  |d         z  z
  |d<   d
| dd         z  |dd         z  dd| dd         dz  z  z   d	| dd         z  z
  |dd         z  z   d	| dd         z  |dd         z  z
  |dd<   d
| d         z  |d         z  d|d         z  z   |d<   |S )a  
    Product of the Hessian matrix of the Rosenbrock function with a vector.

    Parameters
    ----------
    x : array_like
        1-D array of points at which the Hessian matrix is to be computed.
    p : array_like
        1-D array, the vector to be multiplied by the Hessian matrix.

    Returns
    -------
    rosen_hess_prod : ndarray
        The Hessian matrix of the Rosenbrock function at `x` multiplied
        by the vector `p`.

    See Also
    --------
    rosen, rosen_der, rosen_hess

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.optimize import rosen_hess_prod
    >>> X = 0.1 * np.arange(9)
    >>> p = 0.5 * np.arange(9)
    >>> rosen_hess_prod(X, p)
    array([  -0.,   27.,  -10.,  -95., -192., -265., -278., -195., -180.])

    r!   r   r   r   r   r   r   r   r   r   Nr   r   r   r   )	r.   r   r   r   r   r   r   r   r   )r=   pr   Hps       r?   r   r     s   > 
A		BqqR(((A	zz!':&& /IIaB-..


1AG
$$A	!'!*AG	,	,BAaD!G^cAaDj(1,!4sQqTzAaD7HHBqEq"v#2#&ta"gqj((3122;6!AbD'ABa"g!""%&BqtH AbE\AbE!C"I-BrFIrA   c                 0     dg d fS  fd}|fS )Nr   c                 .   dxx         dz  cc<    t          j        |           g|z   R  }t          j        |          sQ	 t          j        |                                          }n)# t
          t          f$ r}t          d          |d }~ww xY w|S )Nr   r!   @The user-provided objective function must return a scalar value.)rC   rE   isscalarr   item	TypeErrorru   )r=   wrapper_argsfxerF   functionncallss       r?   function_wrapperz/_wrap_scalar_function.<locals>.function_wrapper  s    q			Q			Xbgajj9L4$7999 {2 	GGZ^^((**z* G G G  "? @ @EFGG 	s   &A, ,B=BBrR   )r   rF   r   r   s   `` @r?   _wrap_scalar_functionr     sO     SFt|       ###rA   c                       e Zd ZdS )_MaxFuncCallErrorNro   rR   rA   r?   r   r     rp   rA   r   c                 4     dg d fS  fd}|fS )Nr   c                 d   d         k    rt          d          dxx         dz  cc<    t          j        |           g|z   R  }t          j        |          sQ	 t          j        |                                          }n)# t          t          f$ r}t          d          |d }~ww xY w|S )Nr   zToo many function callsr!   r   )r   rC   rE   r   r   r   r   ru   )r=   r   r   r   rF   r   maxfunr   s       r?   r   zA_wrap_scalar_function_maxfun_validation.<locals>.function_wrapper  s    !9#$=>>>q			Q			Xbgajj9L4$7999 {2 	GGZ^^((**z* G G G  "? @ @EFGG 	s    &B B-B((B-rR   )r   rF   r   r   r   s   ``` @r?   '_wrap_scalar_function_maxfun_validationr     sU     SFt|       " ###rA   -C6?c                     ||||||	|d}t          |
          }
t          | ||fd|
i|}|r5|d         |d         |d         |d         |d         f}|	r||d         fz  }|S |	r|d         |d         fS |d         S )	a(  
    Minimize a function using the downhill simplex algorithm.

    This algorithm only uses function values, not derivatives or second
    derivatives.

    Parameters
    ----------
    func : callable func(x,*args)
        The objective function to be minimized.
    x0 : ndarray
        Initial guess.
    args : tuple, optional
        Extra arguments passed to func, i.e., ``f(x,*args)``.
    xtol : float, optional
        Absolute error in xopt between iterations that is acceptable for
        convergence.
    ftol : number, optional
        Absolute error in func(xopt) between iterations that is acceptable for
        convergence.
    maxiter : int, optional
        Maximum number of iterations to perform.
    maxfun : number, optional
        Maximum number of function evaluations to make.
    full_output : bool, optional
        Set to True if fopt and warnflag outputs are desired.
    disp : bool, optional
        Set to True to print convergence messages.
    retall : bool, optional
        Set to True to return list of solutions at each iteration.
    callback : callable, optional
        Called after each iteration, as callback(xk), where xk is the
        current parameter vector.
    initial_simplex : array_like of shape (N + 1, N), optional
        Initial simplex. If given, overrides `x0`.
        ``initial_simplex[j,:]`` should contain the coordinates of
        the jth vertex of the ``N+1`` vertices in the simplex, where
        ``N`` is the dimension.

    Returns
    -------
    xopt : ndarray
        Parameter that minimizes function.
    fopt : float
        Value of function at minimum: ``fopt = func(xopt)``.
    iter : int
        Number of iterations performed.
    funcalls : int
        Number of function calls made.
    warnflag : int
        1 : Maximum number of function evaluations made.
        2 : Maximum number of iterations reached.
    allvecs : list
        Solution at each iteration.

    See also
    --------
    minimize: Interface to minimization algorithms for multivariate
        functions. See the 'Nelder-Mead' `method` in particular.

    Notes
    -----
    Uses a Nelder-Mead simplex algorithm to find the minimum of function of
    one or more variables.

    This algorithm has a long history of successful use in applications.
    But it will usually be slower than an algorithm that uses first or
    second derivative information. In practice, it can have poor
    performance in high-dimensional problems and is not robust to
    minimizing complicated functions. Additionally, there currently is no
    complete theory describing when the algorithm will successfully
    converge to the minimum, or how fast it will if it does. Both the ftol and
    xtol criteria must be met for convergence.

    Examples
    --------
    >>> def f(x):
    ...     return x**2

    >>> from scipy import optimize

    >>> minimum = optimize.fmin(f, 1)
    Optimization terminated successfully.
             Current function value: 0.000000
             Iterations: 17
             Function evaluations: 34
    >>> minimum[0]
    -8.8817841970012523e-16

    References
    ----------
    .. [1] Nelder, J.A. and Mead, R. (1965), "A simplex method for function
           minimization", The Computer Journal, 7, pp. 308-313

    .. [2] Wright, M.H. (1996), "Direct Search Methods: Once Scorned, Now
           Respectable", in Numerical Analysis 1995, Proceedings of the
           1995 Dundee Biennial Conference in Numerical Analysis, D.F.
           Griffiths and G.A. Watson (Eds.), Addison Wesley Longman,
           Harlow, UK, pp. 191-208.

    )xatolfatolr2   r1   disp
return_allinitial_simplexr\   r=   r:   nitnfevstatusallvecs)rl   _minimize_neldermead)r   r   rF   xtolftolr2   r   full_outputr   retallr\   r   optsr[   retlists                  r?   r   r   -  s    N  .0 0D h''H
tR
I
I
ID
I
IC 	c(CJE
CKXN 	*I))G 	s8S^++s8OrA   Fc                    t          |           |}|}t          j        |                                          }t          j        |j        t          j                  r|j        nt          j        }t          j        ||          }|r:t          t          |                    }d}dd|z  z   }ddd|z  z  z
  }dd|z  z
  }nd}d}d}d}d}d}||j        |j        }}||k                                    rt          d	          t          j        ||k              st          j        ||k              rt          j        d
t"          d           |t          j        |||          }|t          |          }t          j        |dz   |f|j                  }||d<   t)          |          D ]C}t          j        |d          }||         dk    rd|z   ||         z  ||<   n|||<   |||dz   <   Dnt          j        |                                          }t          j        |j        t          j                  r|j        nt          j        }t          j        ||          }|j        dk    s|j        d         |j        d         dz   k    rt          d          t          |          |j        d         k    rt          d          |j        d         }|r	|d         g}|||dz  }|dz  }nI|#|t          j        k    r|dz  }n1t          j        }n$|"|t          j        k    r|dz  }nt          j        }|8||k    }t          j        |d|z  |z
  |          }t          j        |||          }t9          t)          d|dz                       } t          j        |dz   ft          j        t                    }!t=          | ||          \  }"} 	 t)          |dz             D ]} | ||                   |!|<   n# t>          $ r Y nw xY wt          j         |!          }#t          j!        ||#d          }t          j!        |!|#d          }!nE# t          j         |!          }#t          j!        ||#d          }t          j!        |!|#d          }!w xY wt          j         |!          }#t          j!        |!|#d          }!t          j!        ||#d          }d}$|"d         |k     rR|$|k     rK	 t          j"        t          j#        t          j$        |dd         |d         z
                                |	k    rt          j"        t          j$        |!d         |!dd         z
                      |
k    r	 t          j         |!          }#t          j!        ||#d          }t          j!        |!|#d          }!|r|%                    |d                    tM          |d         |!d                   }%tO          ||%          rn5n3t          j(        )                    |dd         d          |z  }&d|z   |&z  ||d         z  z
  }'|t          j        |'||          }' | |'          }(d})|(|!d         k     r[d||z  z   |&z  ||z  |d         z  z
  }*|t          j        |*||          }* | |*          }+|+|(k     r|*|d<   |+|!d<   n-|'|d<   |(|!d<   n!|(|!d         k     r|'|d<   |(|!d<   n	|(|!d         k     rQd||z  z   |&z  ||z  |d         z  z
  },|t          j        |,||          }, | |,          }-|-|(k    r|,|d<   |-|!d<   nSd})nPd|z
  |&z  ||d         z  z   }.|t          j        |.||          }. | |.          }/|/|!d         k     r|.|d<   |/|!d<   nd})|)rZ| D ]W}0|d         |||0         |d         z
  z  z   ||0<   |t          j        ||0         ||          ||0<    | ||0                   |!|0<   X|$dz  }$n# t>          $ r Y nw xY wt          j         |!          }#t          j!        ||#d          }t          j!        |!|#d          }!|r|%                    |d                    tM          |d         |!d                   }%tO          ||%          rnn# t          j         |!          }#t          j!        ||#d          }t          j!        |!|#d          }!|r|%                    |d                    tM          |d         |!d                   }%tO          ||%          r Y nw xY w|"d         |k     r|$|k     K|d         }1t          j*        |!          }2d}3|"d         |k    r.d}3tV          d         }4|rt          j        |4tX          d           n|$|k    r.d}3tV          d         }4|rt          j        |4tX          d           n[tV          d         }4|rLt[          |4           t[          d|2d           t[          d|$z             t[          d|"d         z             tM          |2|$|"d         |3|3dk    |4|1||!f          }5|r||5d<   |5S )aj  
    Minimization of scalar function of one or more variables using the
    Nelder-Mead algorithm.

    Options
    -------
    disp : bool
        Set to True to print convergence messages.
    maxiter, maxfev : int
        Maximum allowed number of iterations and function evaluations.
        Will default to ``N*200``, where ``N`` is the number of
        variables, if neither `maxiter` or `maxfev` is set. If both
        `maxiter` and `maxfev` are set, minimization will stop at the
        first reached.
    return_all : bool, optional
        Set to True to return a list of the best solution at each of the
        iterations.
    initial_simplex : array_like of shape (N + 1, N)
        Initial simplex. If given, overrides `x0`.
        ``initial_simplex[j,:]`` should contain the coordinates of
        the jth vertex of the ``N+1`` vertices in the simplex, where
        ``N`` is the dimension.
    xatol : float, optional
        Absolute error in xopt between iterations that is acceptable for
        convergence.
    fatol : number, optional
        Absolute error in func(xopt) between iterations that is acceptable for
        convergence.
    adaptive : bool, optional
        Adapt algorithm parameters to dimensionality of problem. Useful for
        high-dimensional minimization [1]_.
    bounds : sequence or `Bounds`, optional
        Bounds on variables. There are two ways to specify the bounds:

        1. Instance of `Bounds` class.
        2. Sequence of ``(min, max)`` pairs for each element in `x`. None
           is used to specify no bound.

        Note that this just clips all vertices in simplex based on
        the bounds.

    References
    ----------
    .. [1] Gao, F. and Han, L.
       Implementing the Nelder-Mead simplex algorithm with adaptive
       parameters. 2012. Computational Optimization and Applications.
       51:1, pp. 259-277

    r   r!   r   g      ?      ?g?gMb0?NzENelder Mead - one of the lower bounds is greater than an upper bound.0Initial guess is not within the specified boundsr   rz   r   T)rE   z5`initial_simplex` should be an array of shape (N+1,N)z5Size of `initial_simplex` is not consistent with `x0`r   r=   r:   r   r   r1   r2   r0   !         Current function value: f         Iterations: %d!         Function evaluations: %d)r:   r   r   r   r0   messager=   final_simplexr   ).r   rC   
atleast_1dflatten
issubdtyper   inexactfloat64r   floatlenlbubr   ru   r   r   r   r   emptyrangearray
atleast_2drE   r   r   r   wherelistfullr   r   argsorttakemaxravelr   appendr   r*   addreducemin_status_messager   print)6r   r   rF   r\   r2   r1   r   r   r   r   r   adaptiver   r   r   r   r   dimrhochipsisigmanonzdeltzdeltlower_boundupper_boundNsimkyr   mskone2np1fsimfcallsind
iterationsrX   xbarxrfxrdoshrinkxefxexcfxcxccfxccjr=   fvalwarnflagr   results6                                                         r?   r   r     s8   l ?+++FF	r			"	"	$	$Bbh
;;KBHHE	Be	$	$	$B 
CGGnn!C%iQ#YAcE	HE#)9fi[+%**,, 	@ ? @ @ @6+"## 	9rvb;.>'?'? 	9ML)a9 9 9 9 WRk22GGhAqz222Aq 	 	A$'''AtqyyHad*!!CAJJ	 mO,,1133]39bjAAQ		rzjE***8q==CIaLCIaL1,<<<TUUUr77cil""TUUUIaL q6( 6>c'S	 RV#gGGfGG	bfWFFVF KhsAkMC/55gc;445AE??##G7AE8RV5111D:4vNNLFD%q1u 	# 	#Ad3q6llDGG	#    jgc3""wtS!$$ jgc3""wtS!$$$$$$
*T

C74a  D
'#sA

CJ!9v*w"6"6H	rxs122wQ'7 8 899::eCCF26$q'DH"45566%??| *T""C'#sA&&C74a((D 's1v&&&"03q6tAw"G"G"G(3FGG E 6==SbS1--1Dc'T!C#b'M1B!WRk::$r((CHT!W}}#)mt+cCi#b'.AA%[+>>Bd2hh99 CG"DHH CG"DHHb>> CG"DHH T"X~~#)mt3cCi#b'6II!-!#[+!F!FB"d2hh#::&(CG'*DHH'(HH  !3w$.s2w>!-"$'#{K"H"HC#tCyy$r(??&)CG'+DHH'(H 3!( 3 3A%(Ves1vA.G%GCF%1)+$'FK*F *FA&*d3q6llDGG!OJJ  	 	 	D	 *T""C'#sA&&C74a((D 's1v&&&"03q6tAw"G"G"G(3FGG  *T""C'#sA&&C74a((D 's1v&&&"03q6tAw"G"G"G(3FGG S !9v*w"6"6V 	AA6$<<DHayFh' 	=M#~!<<<<	w		i( 	=M#~!<<<<i( 	C#JJJ>d>>>???+j89995q	ABBB*6!9#+h!m$'1S$KI I IF  $#yMsd   )P  ?Q  
P
Q PQ AR-B_6 G1_6 5b 6
` b `b Bd! d!c                 r    t          j        | t                    }  || g|R  }t          || d|||          S )a  Finite difference approximation of the derivatives of a
    scalar or vector-valued function.

    If a function maps from :math:`R^n` to :math:`R^m`, its derivatives form
    an m-by-n matrix
    called the Jacobian, where an element :math:`(i, j)` is a partial
    derivative of f[i] with respect to ``xk[j]``.

    Parameters
    ----------
    xk : array_like
        The coordinate vector at which to determine the gradient of `f`.
    f : callable
        Function of which to estimate the derivatives of. Has the signature
        ``f(xk, *args)`` where `xk` is the argument in the form of a 1-D array
        and `args` is a tuple of any additional fixed parameters needed to
        completely specify the function. The argument `xk` passed to this
        function is an ndarray of shape (n,) (never a scalar even if n=1).
        It must return a 1-D array_like of shape (m,) or a scalar.

        Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
        ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
        Rather than passing ``f0`` as the callable, wrap it to accept
        only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
        callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
        gathered before invoking this function.

        .. versionchanged:: 1.9.0
            `f` is now able to return a 1-D array-like, with the :math:`(m, n)`
            Jacobian being estimated.

    epsilon : {float, array_like}, optional
        Increment to `xk` to use for determining the function gradient.
        If a scalar, uses the same finite difference delta for all partial
        derivatives. If an array, should contain one value per element of
        `xk`. Defaults to ``sqrt(np.finfo(float).eps)``, which is approximately
        1.49e-08.
    \*args : args, optional
        Any other arguments that are to be passed to `f`.

    Returns
    -------
    jac : ndarray
        The partial derivatives of `f` to `xk`.

    See Also
    --------
    check_grad : Check correctness of gradient function against approx_fprime.

    Notes
    -----
    The function gradient is determined by the forward finite difference
    formula::

                 f(xk[i] + epsilon[i]) - f(xk[i])
        f'[i] = ---------------------------------
                            epsilon[i]

    Examples
    --------
    >>> import numpy as np
    >>> from scipy import optimize
    >>> def func(x, c0, c1):
    ...     "Coordinate vector `x` should be an array of size two."
    ...     return c0 * x[0]**2 + c1*x[1]**2

    >>> x = np.ones(2)
    >>> c0, c1 = (1, 200)
    >>> eps = np.sqrt(np.finfo(float).eps)
    >>> optimize.approx_fprime(x, func, [eps, np.sqrt(200) * eps], c0, c1)
    array([   2.        ,  400.00004208])

    r   )rj   abs_steprF   f0)rC   r   r  r%   )xkr   r   rF   r;  s        r?   r   r     sM    T 
B		B	
2BQ9w"&2/ / / /rA   seed   )position_numrD   )r   	directionrngc                L   |}t          j        |          }d }|dk    rt          j         ||g|R            }	|	j        dk    rt	          d          t          |          }
|
                    |j                  }| ||f|z   }|}t          j        d          }t          j	        |	|          }n(|dk    r|}| }|} ||g|R  }nt	          | d          t          j
        t          j        t          j        |t          |||g|R  z
  d	z                                S )
al	  Check the correctness of a gradient function by comparing it against a
    (forward) finite-difference approximation of the gradient.

    Parameters
    ----------
    func : callable ``func(x0, *args)``
        Function whose derivative is to be checked.
    grad : callable ``grad(x0, *args)``
        Jacobian of `func`.
    x0 : ndarray
        Points to check `grad` against forward difference approximation of grad
        using `func`.
    args : \\*args, optional
        Extra arguments passed to `func` and `grad`.
    epsilon : float, optional
        Step size used for the finite difference approximation. It defaults to
        ``sqrt(np.finfo(float).eps)``, which is approximately 1.49e-08.
    direction : str, optional
        If set to ``'random'``, then gradients along a random vector
        are used to check `grad` against forward difference approximation
        using `func`. By default it is ``'all'``, in which case, all
        the one hot direction vectors are considered to check `grad`.
        If `func` is a vector valued function then only ``'all'`` can be used.
    rng : `numpy.random.Generator`, optional
        Pseudorandom number generator state. When `rng` is None, a new
        `numpy.random.Generator` is created using entropy from the
        operating system. Types other than `numpy.random.Generator` are
        passed to `numpy.random.default_rng` to instantiate a ``Generator``.

        The random numbers generated affect the random vector along which gradients
        are computed to check ``grad``. Note that `rng` is only used when `direction`
        argument is set to `'random'`.

    Returns
    -------
    err : float
        The square root of the sum of squares (i.e., the 2-norm) of the
        difference between ``grad(x0, *args)`` and the finite difference
        approximation of `grad` using func at the points `x0`.

    See Also
    --------
    approx_fprime

    Examples
    --------
    >>> import numpy as np
    >>> def func(x):
    ...     return x[0]**2 - 0.5 * x[1]**3
    >>> def grad(x):
    ...     return [2 * x[0], -1.5 * x[1]**2]
    >>> from scipy.optimize import check_grad
    >>> check_grad(func, grad, [1.5, -1.5])
    2.9802322387695312e-08  # may vary
    >>> rng = np.random.default_rng()
    >>> check_grad(func, grad, [1.5, -1.5],
    ...             direction='random', seed=rng)
    2.9802322387695312e-08

    c                       ||| |z  z   g|R  S r9   rR   )wr   r   vrF   s        r?   gzcheck_grad.<locals>.gL  s"    tB1H$t$$$$rA   randomr!   z1'random' can only be used with scalar valued func)r   r!   rD   z1 is not a valid string for ``direction`` argumentr   )rC   r   
asanyarrayr   ru   r(   standard_normalr   r   dotr   r   r   r   )r   r   r   r   r@  rA  rF   steprF  _gradrng_genrE  _args_funcvarsanalytical_grads                   r?   r   r   
  sq   ~ D	BB% % % Hdd2oooo..:>> % & & &$S))##"(#44r1$x~~&**	e		$r/D///I 2 2 2 3 3 	3 726"&	=udCUCCC	CaG      rA   c                 B     || f|z    } || ||z  z   f|z    }||z
  |z  S r9   rR   )r   r   fprimer   rF   f1f2s          r?   approx_fhess_prW  h  s?    	2%$,	 B	2	>#d*	,BGwrA   c                       e Zd ZdS )_LineSearchErrorNro   rR   rA   r?   rY  rY  o  rp   rA   rY  c           
         |                     dd          }t          | ||||||fi |}	|	d         2|0||	d         |z  z   }
 ||	d         |
|	d         |	d                   sd}	|	d         pt          j                    5  t          j        dt
                     i }dD ]}||v r||         ||<   t          | ||||||fd|i|}	ddd           n# 1 swxY w Y   |	d         t                      |	S )	a  
    Same as line_search_wolfe1, but fall back to line_search_wolfe2 if
    suitable step length is not found, and raise an exception if a
    suitable step length is not found.

    Raises
    ------
    _LineSearchError
        If no suitable step size is found

    extra_conditionNr   r      r9   ignore)c1c2r   )popr"   r   catch_warningssimplefilterr$   r#   rY  )r   rT  r<  pkgfkold_fvalold_old_fvalkwargsr[  retxp1kwargs2keys                r?   _line_search_wolfe12rl  s  s    jj!2D99O
QB%|' '%' 'C 1vo93q6B;s1vsCFCF;; 	C
1v~$&& 		0 		0!(,=>>>G+ / /&==#)#;GCL$QB%-|0 05D0 (/0 0C		0 		0 		0 		0 		0 		0 		0 		0 		0 		0 		0 		0 		0 		0 		0 1v~   Js   ?ACCCh㈵>g?c                    ||||	||
||||d
}t          |          }t          | |||fd|i|}|rC|d         |d         |d         |d         |d         |d         |d	         f}|
r||d
         fz  }|S |
r|d         |d
         fS |d         S )a  
    Minimize a function using the BFGS algorithm.

    Parameters
    ----------
    f : callable ``f(x,*args)``
        Objective function to be minimized.
    x0 : ndarray
        Initial guess, shape (n,)
    fprime : callable ``f'(x,*args)``, optional
        Gradient of f.
    args : tuple, optional
        Extra arguments passed to f and fprime.
    gtol : float, optional
        Terminate successfully if gradient norm is less than `gtol`
    norm : float, optional
        Order of norm (Inf is max, -Inf is min)
    epsilon : int or ndarray, optional
        If `fprime` is approximated, use this value for the step size.
    callback : callable, optional
        An optional user-supplied function to call after each
        iteration. Called as ``callback(xk)``, where ``xk`` is the
        current parameter vector.
    maxiter : int, optional
        Maximum number of iterations to perform.
    full_output : bool, optional
        If True, return ``fopt``, ``func_calls``, ``grad_calls``, and
        ``warnflag`` in addition to ``xopt``.
    disp : bool, optional
        Print convergence message if True.
    retall : bool, optional
        Return a list of results at each iteration if True.
    xrtol : float, default: 0
        Relative tolerance for `x`. Terminate successfully if step
        size is less than ``xk * xrtol`` where ``xk`` is the current
        parameter vector.
    c1 : float, default: 1e-4
        Parameter for Armijo condition rule.
    c2 : float, default: 0.9
        Parameter for curvature condition rule.
    hess_inv0 : None or ndarray, optional``
        Initial inverse hessian estimate, shape (n, n). If None (default) then
        the identity matrix is used.

    Returns
    -------
    xopt : ndarray
        Parameters which minimize f, i.e., ``f(xopt) == fopt``.
    fopt : float
        Minimum value.
    gopt : ndarray
        Value of gradient at minimum, f'(xopt), which should be near 0.
    Bopt : ndarray
        Value of 1/f''(xopt), i.e., the inverse Hessian matrix.
    func_calls : int
        Number of function_calls made.
    grad_calls : int
        Number of gradient calls made.
    warnflag : integer
        1 : Maximum number of iterations exceeded.
        2 : Gradient and/or function calls not changing.
        3 : NaN result encountered.
    allvecs : list
        The value of `xopt` at each iteration. Only returned if `retall` is
        True.

    Notes
    -----
    Optimize the function, `f`, whose gradient is given by `fprime`
    using the quasi-Newton method of Broyden, Fletcher, Goldfarb,
    and Shanno (BFGS).

    Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.

    See Also
    --------
    minimize: Interface to minimization algorithms for multivariate
        functions. See ``method='BFGS'`` in particular.

    References
    ----------
    Wright, and Nocedal 'Numerical Optimization', 1999, p. 198.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.optimize import fmin_bfgs
    >>> def quadratic_cost(x, Q):
    ...     return x @ Q @ x
    ...
    >>> x0 = np.array([-3, -4])
    >>> cost_weight =  np.diag([1., 10.])
    >>> # Note that a trailing comma is necessary for a tuple with single element
    >>> fmin_bfgs(quadratic_cost, x0, args=(cost_weight,))
    Optimization terminated successfully.
            Current function value: 0.000000
            Iterations: 7                   # may vary
            Function evaluations: 24        # may vary
            Gradient evaluations: 8         # may vary
    array([ 2.85169950e-06, -4.61820139e-07])

    >>> def quadratic_cost_grad(x, Q):
    ...     return 2 * Q @ x
    ...
    >>> fmin_bfgs(quadratic_cost, x0, quadratic_cost_grad, args=(cost_weight,))
    Optimization terminated successfully.
            Current function value: 0.000000
            Iterations: 7
            Function evaluations: 8
            Gradient evaluations: 8
    array([ 2.85916637e-06, -4.54371951e-07])

    )
gtolnormepsr   r2   r   xrtolr^  r_  	hess_inv0r\   r=   r:   r;   hess_invr   njevr   r   )rl   _minimize_bfgs)r   r   rT  rF   ro  rp  r   r2   r   r   r   r\   rr  r^  r_  rs  r   r[   r   s                      r?   r   r     s    j  "	$ 	$D h''H
Bf
H
Hx
H4
H
HC 
s8SZUS_v;FS]< 	*I))G 	s8S^++s8OrA   c                    t          |           t          |           |
}t          |                                          }|j        dk    rd|_        |t          |          dz  }t          | |||||          }|j        }|j	        } ||          } ||          }d}t          |          }t          j        |t                    }||n|}|t          j                            |          dz  z   }|}|r|g}d}t          ||          }||k    r||k     r
t          j        ||           } 	 t#          |||| |||d	d
||          \  }!}"}#}}}$n# t$          $ r d}Y nw xY w|!| z  }%||%z   }&|r|                    |&           |&}|$ ||&          }$|$|z
  }'|$}|dz  }t)          ||          }(t+          ||(          rn_t          ||          }||k    rnF|!t          |           z  ||t          |          z   z  k    rnt          j        |          sd}nt          j        |'|%          })|)dk    rd}*|	rd}+t/          d|+           nd|)z  }*||%ddt          j        f         |'t          j        ddf         z  |*z  z
  },||'ddt          j        f         |%t          j        ddf         z  |*z  z
  }-t          j        |,t          j        ||-                    |*|%ddt          j        f         z  |%t          j        ddf         z  z   }||k    r||k     
|}.|dk    rt2          d         }+n||k    rd}t2          d         }+nkt          j        |          s:t          j        |.          s&t          j        |                                          rd}t2          d         }+nt2          d         }+|	rct/          ||+           t9          d|.d           t9          d|z             t9          d|j        z             t9          d|j        z             t)          |.|||j        |j        ||dk    |+||
  
        }/|r||/d<   |/S )a  
    Minimization of scalar function of one or more variables using the
    BFGS algorithm.

    Options
    -------
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        Maximum number of iterations to perform.
    gtol : float
        Terminate successfully if gradient norm is less than `gtol`.
    norm : float
        Order of norm (Inf is max, -Inf is min).
    eps : float or ndarray
        If `jac is None` the absolute step size used for numerical
        approximation of the jacobian via forward differences.
    return_all : bool, optional
        Set to True to return a list of the best solution at each of the
        iterations.
    finite_diff_rel_step : None or array_like, optional
        If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
        use for numerical approximation of the jacobian. The absolute step
        size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
        possibly adjusted to fit into the bounds. For ``jac='3-point'``
        the sign of `h` is ignored. If None (default) then step is selected
        automatically.
    xrtol : float, default: 0
        Relative tolerance for `x`. Terminate successfully if step size is
        less than ``xk * xrtol`` where ``xk`` is the current parameter vector.
    c1 : float, default: 1e-4
        Parameter for Armijo condition rule.
    c2 : float, default: 0.9
        Parameter for curvature condition rule.
    hess_inv0 : None or ndarray, optional
        Initial inverse hessian estimate, shape (n, n). If None (default) then
        the identity matrix is used.

    Notes
    -----
    Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.

    If minimization doesn't complete successfully, with an error message of
    ``Desired error not necessarily achieved due to precision loss``, then
    consider setting `gtol` to a higher value. This precision loss typically
    occurs when the (finite difference) numerical differentiation cannot provide
    sufficient precision to satisfy the `gtol` termination criterion.
    This can happen when working in single precision and a callable jac is not
    provided. For single precision problems a `gtol` of 1e-3 seems to work.
    r   rH  Nr   )rF   r   r   r   r   r   0.++}Ô%IT)r   r   r^  r_  r!   r           g     @@z.Divide-by-zero encountered: rhok assumed largeTr   r3   r2   r   r4   r0   r   r   r   r   !         Gradient evaluations: %d)
r:   r;   rt  r   ru  r   r0   r   r=   r   r   )r   rw   r   r   r   r   r  r   r:   r   rC   r   intlinalgrp  r   rK  rl  rY  r  r   r*   r   _print_success_message_or_warnnewaxisr  isnanr   r  r   ngev)0r:   r   rF   r;   r\   ro  rp  rq  r2   r   r   r   rr  r^  r_  rs  r   r   r   r   myfprimere  rd  r#  r!  Irv   rf  r<  r   r7  gnormrc  alpha_kfcgcgfkp1skxkp1ykrX   rhok_invrhokr   A1A2r6  r8  s0                                                   r?   rv  rv  0  s   n ?+++Y'''F					B	w!||b''C-	!#r3T37K
M 
M 
MB 	AwHquuH
(2,,C	ABA
qAYB binnS11A55L	B $HCT"""E4<<a'kkfRoo	)!Xr2s*2Lv/4D D D ;GRX|UU   	 	 	HE	
 r\Bw 	!NN4   =HTNNES[	Q,rx@@@$X/BCC 	&&&TMM GBKK5%'"++*=#>>>{8$$ 	 H6"b>> r>>D :F.tS999=DAAArzM"R
AAA%66==AAArzM"R
AAA%66==VBr2''4"QQQ
]2C+C13BJM1B,C Du 4<<a'kkz D1}}i(	
gi(	% )BHTNN )bhrll.>.>.@.@ )e$i( =&x555:$:::;;;'!+,,,1BG;<<<1BG;<<<#!#%-]SB !# # #F  $#yMs   7!E E)(E)c                 h    | st          |           d S t          j        ||pt          d           d S )Nr   rz   )r  r   r   r   )r7  r   warntypes      r?   r  r    s<     Jggx:?qIIIIIIrA   g?c                     ||||	||
d}t          |          }t          | |||f|||d|}|r5|d         |d         |d         |d         |d         f}|
r||d         fz  }|S |
r|d         |d         fS |d         S )	a:  
    Minimize a function using a nonlinear conjugate gradient algorithm.

    Parameters
    ----------
    f : callable, ``f(x, *args)``
        Objective function to be minimized. Here `x` must be a 1-D array of
        the variables that are to be changed in the search for a minimum, and
        `args` are the other (fixed) parameters of `f`.
    x0 : ndarray
        A user-supplied initial estimate of `xopt`, the optimal value of `x`.
        It must be a 1-D array of values.
    fprime : callable, ``fprime(x, *args)``, optional
        A function that returns the gradient of `f` at `x`. Here `x` and `args`
        are as described above for `f`. The returned value must be a 1-D array.
        Defaults to None, in which case the gradient is approximated
        numerically (see `epsilon`, below).
    args : tuple, optional
        Parameter values passed to `f` and `fprime`. Must be supplied whenever
        additional fixed parameters are needed to completely specify the
        functions `f` and `fprime`.
    gtol : float, optional
        Stop when the norm of the gradient is less than `gtol`.
    norm : float, optional
        Order to use for the norm of the gradient
        (``-np.inf`` is min, ``np.inf`` is max).
    epsilon : float or ndarray, optional
        Step size(s) to use when `fprime` is approximated numerically. Can be a
        scalar or a 1-D array. Defaults to ``sqrt(eps)``, with eps the
        floating point machine precision.  Usually ``sqrt(eps)`` is about
        1.5e-8.
    maxiter : int, optional
        Maximum number of iterations to perform. Default is ``200 * len(x0)``.
    full_output : bool, optional
        If True, return `fopt`, `func_calls`, `grad_calls`, and `warnflag` in
        addition to `xopt`.  See the Returns section below for additional
        information on optional return values.
    disp : bool, optional
        If True, return a convergence message, followed by `xopt`.
    retall : bool, optional
        If True, add to the returned values the results of each iteration.
    callback : callable, optional
        An optional user-supplied function, called after each iteration.
        Called as ``callback(xk)``, where ``xk`` is the current value of `x0`.
    c1 : float, default: 1e-4
        Parameter for Armijo condition rule.
    c2 : float, default: 0.4
        Parameter for curvature condition rule.

    Returns
    -------
    xopt : ndarray
        Parameters which minimize f, i.e., ``f(xopt) == fopt``.
    fopt : float, optional
        Minimum value found, f(xopt). Only returned if `full_output` is True.
    func_calls : int, optional
        The number of function_calls made. Only returned if `full_output`
        is True.
    grad_calls : int, optional
        The number of gradient calls made. Only returned if `full_output` is
        True.
    warnflag : int, optional
        Integer value with warning status, only returned if `full_output` is
        True.

        0 : Success.

        1 : The maximum number of iterations was exceeded.

        2 : Gradient and/or function calls were not changing. May indicate
            that precision was lost, i.e., the routine did not converge.

        3 : NaN result encountered.

    allvecs : list of ndarray, optional
        List of arrays, containing the results at each iteration.
        Only returned if `retall` is True.

    See Also
    --------
    minimize : common interface to all `scipy.optimize` algorithms for
               unconstrained and constrained minimization of multivariate
               functions. It provides an alternative way to call
               ``fmin_cg``, by specifying ``method='CG'``.

    Notes
    -----
    This conjugate gradient algorithm is based on that of Polak and Ribiere
    [1]_.

    Conjugate gradient methods tend to work better when:

    1. `f` has a unique global minimizing point, and no local minima or
       other stationary points,
    2. `f` is, at least locally, reasonably well approximated by a
       quadratic function of the variables,
    3. `f` is continuous and has a continuous gradient,
    4. `fprime` is not too large, e.g., has a norm less than 1000,
    5. The initial guess, `x0`, is reasonably close to `f` 's global
       minimizing point, `xopt`.

    Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.

    References
    ----------
    .. [1] Wright & Nocedal, "Numerical Optimization", 1999, pp. 120-122.

    Examples
    --------
    Example 1: seek the minimum value of the expression
    ``a*u**2 + b*u*v + c*v**2 + d*u + e*v + f`` for given values
    of the parameters and an initial guess ``(u, v) = (0, 0)``.

    >>> import numpy as np
    >>> args = (2, 3, 7, 8, 9, 10)  # parameter values
    >>> def f(x, *args):
    ...     u, v = x
    ...     a, b, c, d, e, f = args
    ...     return a*u**2 + b*u*v + c*v**2 + d*u + e*v + f
    >>> def gradf(x, *args):
    ...     u, v = x
    ...     a, b, c, d, e, f = args
    ...     gu = 2*a*u + b*v + d     # u-component of the gradient
    ...     gv = b*u + 2*c*v + e     # v-component of the gradient
    ...     return np.asarray((gu, gv))
    >>> x0 = np.asarray((0, 0))  # Initial guess.
    >>> from scipy import optimize
    >>> res1 = optimize.fmin_cg(f, x0, fprime=gradf, args=args)
    Optimization terminated successfully.
             Current function value: 1.617021
             Iterations: 4
             Function evaluations: 8
             Gradient evaluations: 8
    >>> res1
    array([-1.80851064, -0.25531915])

    Example 2: solve the same problem using the `minimize` function.
    (This `myopts` dictionary shows all of the available options,
    although in practice only non-default values would be needed.
    The returned value will be a dictionary.)

    >>> opts = {'maxiter' : None,    # default value.
    ...         'disp' : True,    # non-default value.
    ...         'gtol' : 1e-5,    # default value.
    ...         'norm' : np.inf,  # default value.
    ...         'eps' : 1.4901161193847656e-08}  # default value.
    >>> res2 = optimize.minimize(f, x0, jac=gradf, args=args,
    ...                          method='CG', options=opts)
    Optimization terminated successfully.
            Current function value: 1.617021
            Iterations: 4
            Function evaluations: 8
            Gradient evaluations: 8
    >>> res2.x  # minimum found
    array([-1.80851064, -0.25531915])

    )ro  rp  rq  r   r2   r   r\   r^  r_  r=   r:   r   ru  r   r   )rl   _minimize_cg)r   r   rT  rF   ro  rp  r   r2   r   r   r   r\   r^  r_  r   r[   r   s                    r?   r   r     s    @  " "D h''H
q"dF X"   C  	c(CJFS[#h-O 	*I))G 	s8S^++s8OrA   c                   !"#$%&'( t          |           |
}t          |                                          }|t          |          dz  }t	          | |||||          }|j        }|j        $ ||          } $|          #d}|(|t          j        	                    #          dz  z   }|r(g}d}# %t          #          }d'|k    r||k     rt          j        ##          "dg!d"#$%(fd	&!&'fd	}	 t          |$(%#||||d
d|          \  }}}}}}n# t          $ r d}Y nuw xY w|!d         k    r	!\  }(%#}n &||          \  }(%#}|r|                    (           |dz  }t          (|          }t!          ||          rn|k    r||k     |}|dk    rt"          d         }n||k    rd}t"          d         }nkt          j        |          s:t          j        |          s&t          j        (                                          rd}t"          d         }nt"          d         }|	rct)          ||           t+          d|d           t+          d|z             t+          d|j        z             t+          d|j        z             t          |#|j        |j        ||dk    |(|	  	        } |r|| d<   | S )a  
    Minimization of scalar function of one or more variables using the
    conjugate gradient algorithm.

    Options
    -------
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        Maximum number of iterations to perform.
    gtol : float
        Gradient norm must be less than `gtol` before successful
        termination.
    norm : float
        Order of norm (Inf is max, -Inf is min).
    eps : float or ndarray
        If `jac is None` the absolute step size used for numerical
        approximation of the jacobian via forward differences.
    return_all : bool, optional
        Set to True to return a list of the best solution at each of the
        iterations.
    finite_diff_rel_step : None or array_like, optional
        If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
        use for numerical approximation of the jacobian. The absolute step
        size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
        possibly adjusted to fit into the bounds. For ``jac='3-point'``
        the sign of `h` is ignored. If None (default) then step is selected
        automatically.
    c1 : float, default: 1e-4
        Parameter for Armijo condition rule.
    c2 : float, default: 0.4
        Parameter for curvature condition rule.

    Notes
    -----
    Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
    Nr   )r;   rF   r   r   r   r   rx  g{Gz?c                     | z  z   }| 	|          }|z
  }t          dt          j        ||          z            }| |z  z   }t          |
          }| ||||fS )Nr   rx  )r  rC   rK  r   )alphar  r  r  beta_kpkp1r  deltakrd  r  rp  rc  r<  s          r?   polak_ribiere_powell_stepz/_minimize_cg.<locals>.polak_ribiere_powell_step  s~    
?D} BBF2u--677F6FRK'DEt,,,E4ue44rA   c                      
| |          d d <   \  } }}}}|	k    rdS t          j        ||           t          j        ||          z  k    S )NT)rC   rK  )r  r  fp1r  r<  rc  rd  r  cached_stepro  r  sigma_3s           r?   descent_conditionz'_minimize_cg.<locals>.descent_condition  si     76ueDDKN(3%E2r3 }}t 6"c??whS1A1A&AAArA   ry  rz  )r^  r_  r   r   r[  r!   r   r3   r2   r   r4   r0   r   r   r   r   r|  )	r:   r;   r   ru  r   r0   r   r=   r   r   r9   )r   r   r   r  r   r:   r   rC   r~  rp  r   rK  rl  rY  r  r   r*   r  r  r   r  r  r   r  ))r:   r   rF   r;   r\   ro  rp  rq  r2   r   r   r   r^  r_  r   r   r   r   re  r#  rf  r   r7  r  r  r  r  r  r  rX   r6  r   r8  r  r  rd  r  rc  r  r  r<  s)        ``                          @@@@@@@@r?   r  r    s   R ?+++F					Bb''C-	!#rss7K
M 
M 
MB 	AwHquuH
(2,,C	A	BbinnS11A55L $H
BCT"""EG4<<a'kkS!!f	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5	B 	B 	B 	B 	B 	B 	B 	B"	)!Xr2sH*62"6/4FWY Y Y ;GRX|UU   	 	 	HE	 k!n$$*5'GRS%%*C*CGU*S*S'GRS% 	NN2	Q,rx@@@$X/BCC 	k 4<<a'kkn D1}}i(	
gi(	% )BHTNN )bhrll.>.>.@.@ )e$i( =&x555:$:::;;;'!+,,,1BG;<<<1BG;<<<#BG!#%-]SB !# # #F  $#yMs   "D+ +D:9D:c                    ||||
|d}t          |          }t          | |||||f|||d|}|	r<|d         |d         |d         |d         |d         |d         f}|r||d	         fz  }|S |r|d         |d	         fS |d         S )
a  
    Unconstrained minimization of a function using the Newton-CG method.

    Parameters
    ----------
    f : callable ``f(x, *args)``
        Objective function to be minimized.
    x0 : ndarray
        Initial guess.
    fprime : callable ``f'(x, *args)``
        Gradient of f.
    fhess_p : callable ``fhess_p(x, p, *args)``, optional
        Function which computes the Hessian of f times an
        arbitrary vector, p.
    fhess : callable ``fhess(x, *args)``, optional
        Function to compute the Hessian matrix of f.
    args : tuple, optional
        Extra arguments passed to f, fprime, fhess_p, and fhess
        (the same set of extra arguments is supplied to all of
        these functions).
    epsilon : float or ndarray, optional
        If fhess is approximated, use this value for the step size.
    callback : callable, optional
        An optional user-supplied function which is called after
        each iteration. Called as callback(xk), where xk is the
        current parameter vector.
    avextol : float, optional
        Convergence is assumed when the average relative error in
        the minimizer falls below this amount.
    maxiter : int, optional
        Maximum number of iterations to perform.
    full_output : bool, optional
        If True, return the optional outputs.
    disp : bool, optional
        If True, print convergence message.
    retall : bool, optional
        If True, return a list of results at each iteration.
    c1 : float, default: 1e-4
        Parameter for Armijo condition rule.
    c2 : float, default: 0.9
        Parameter for curvature condition rule

    Returns
    -------
    xopt : ndarray
        Parameters which minimize f, i.e., ``f(xopt) == fopt``.
    fopt : float
        Value of the function at xopt, i.e., ``fopt = f(xopt)``.
    fcalls : int
        Number of function calls made.
    gcalls : int
        Number of gradient calls made.
    hcalls : int
        Number of Hessian calls made.
    warnflag : int
        Warnings generated by the algorithm.
        1 : Maximum number of iterations exceeded.
        2 : Line search failure (precision loss).
        3 : NaN result encountered.
    allvecs : list
        The result at each iteration, if retall is True (see below).

    See also
    --------
    minimize: Interface to minimization algorithms for multivariate
        functions. See the 'Newton-CG' `method` in particular.

    Notes
    -----
    Only one of `fhess_p` or `fhess` need to be given.  If `fhess`
    is provided, then `fhess_p` will be ignored. If neither `fhess`
    nor `fhess_p` is provided, then the hessian product will be
    approximated using finite differences on `fprime`. `fhess_p`
    must compute the hessian times an arbitrary vector. If it is not
    given, finite-differences on `fprime` are used to compute
    it.

    Newton-CG methods are also called truncated Newton methods. This
    function differs from scipy.optimize.fmin_tnc because

    1. scipy.optimize.fmin_ncg is written purely in Python using NumPy
        and scipy while scipy.optimize.fmin_tnc calls a C function.
    2. scipy.optimize.fmin_ncg is only for unconstrained minimization
        while scipy.optimize.fmin_tnc is for unconstrained minimization
        or box constrained minimization. (Box constraints give
        lower and upper bounds for each variable separately.)

    Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.

    References
    ----------
    Wright & Nocedal, 'Numerical Optimization', 1999, p. 140.

    )r   rq  r2   r   r   r  r=   r:   r   ru  nhevr   r   )rl   _minimize_newtoncg)r   r   rT  fhess_pfhessrF   avextolr   r2   r   r   r   r\   r^  r_  r   r[   r   s                     r?   r   r   9  s    B  	" "D h''H
QD&% F&.2"F F@DF FC  
s8SZVc&kv;H/ 	*I))G 	s8S^++s8OrA   c                 8	  
456789:; t          |           |t          d          |}|}|}|}|9t          |                                          }t	          | |||||          ::j        }:j        }:                    |          }|t          v st          |t                    r	d}:fd}|}4
56789:;f	d}d6|	t          |          dz  }	dt          |          z  }t          |          |z  }t          j        t                    j        }t          j        |          ;9r;g4d7d5 ||          8d}t          j        t          j                  j        }||k    r׉7|	k    rd	t&          d
         z   } |d|          S  |;           }t          j                            |d          }t-          dt/          j        |                    }||z  } t3          t          |          |j                  }!| }"|" }#d}$t          j        |"|"          }%|:                    ;          }&6dz  6t9          |          D ]}'t          j                            t          j        |"                    | k    r n|%|tA          ;|#||          }(n% |;|#g|R  }(6dz  6n|&                    |#          }(t          |(          !                                }(t          j        |#|(          })d|)cxk    r	d|z  k    rn n nh|)dk     r|$dk    r nZ|%|) z  |z  }! nO|%|)z  }*|!|*|#z  z  }!|"|*|(z  z  }"t          j        |"|"          }+|+|%z  },|" |,|#z  z   }#|$dz  }$|+}%d} |d|          S |!}-| 5	 tE          ||;|-58|||	  	        \  }.}/}08}}1n,# tF          $ r d	t&          d         z   } |d|          cY S w xY w|.|-z  }2;|2z  ;9r4$                    ;           7dz  7tK          ;8          }3tM          ||3          r |dd          S t          j                            |2d          }||k    t          j'        8          st          j'        |          r |dt&          d                   S t&          d         } |d|          S )ap  
    Minimization of scalar function of one or more variables using the
    Newton-CG algorithm.

    Note that the `jac` parameter (Jacobian) is required.

    Options
    -------
    disp : bool
        Set to True to print convergence messages.
    xtol : float
        Average relative error in solution `xopt` acceptable for
        convergence.
    maxiter : int
        Maximum number of iterations to perform.
    eps : float or ndarray
        If `hessp` is approximated, use this value for the step size.
    return_all : bool, optional
        Set to True to return a list of the best solution at each of the
        iterations.
    c1 : float, default: 1e-4
        Parameter for Armijo condition rule.
    c2 : float, default: 0.9
        Parameter for curvature condition rule.

    Notes
    -----
    Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
    Nz)Jacobian is required for Newton-CG method)rF   r   r   c                 T                         |                               |          S r9   )r   rK  )r=   r   rF   r   s      r?   _hesspz"_minimize_newtoncg.<locals>._hessp  s    771::>>!$$$rA   c                 V  	 rut          | |           t          d	d           t          dz             t          dj        z             t          dj        z             t          dz             	}t	          |j        j        | | dk    |
  
        }
r|d	<   |S )
Nr   r   r   r   r|  z          Hessian evaluations: %dr   )
r:   r;   r   ru  r  r   r0   r   r=   r   r   )r  r  r   r  r   )r7  r   r6  r8  r   r   rd  hcallsr#  re  r   r   r<  s       r?   	terminatez%_minimize_newtoncg.<locals>.terminate  s     	?*8S999BhBBBCCC+a/0005?@@@5?@@@4v=>>>Dc%'W6()1Q$%' ' '  	( 'F9rA   r   r      z	Warning: r2   r!   rx  r   r   r   zMWarning: CG iterations didn't converge. The Hessian is not positive definite.)r^  r_  r3   r   r   r\   r4   r0   )(r   ru   r   r   r   r:   r   r   r-   
isinstancer    r  rC   finfor  r  rE   r  rq  r  r~  rp  r  mathr   r   r   rK  r  r  r  r   rW  squeezerl  rY  r  r   r*   r  )<r:   r   rF   r;   r   hesspr\   r   rq  r2   r   r   r^  r_  r   r  r  r  r   r   rT  _hr  r  
cg_maxiterupdate_l1normrf  
float64epsr   bmaggradetatermcondxsupiripsupiidri0rs   k2Apcurvalphaidri1betairc  alphakr  r  r  updaterX   r   rd  r  r#  re  r   r   r<  s<             `                                         @@@@@@@@r?   r  r    s   B ?+++
{DEEEGEGGF					B	!R44
 
 
B 	AWF	B 	
j^<<	% 	% 	% 	% 	%             " Fb''#+CGGJr77WDHUOO'M	B $	A
CquuHL"*%%)J
$

<<	 ::C9Q$$$ VBZZK)...**#ty))**=c"ggRX...Rvb"~~AaKF
## %	% %	%Bv}}RVBZZ((H44}?'E67CCBB U2T222BaKFF UU5\\$$&&B6%$$DD****A
N*****EEE !TENQ.EED[FVe^#E&2+B6"b>>D4KEC%%-'EFADD(C9Q$$$b	%)!VRS*2LRBP P P :FBHlEE   	% 	% 	%	 ::C9Q$$$$$	%
 "
f 	NN2	Q,rx@@@$X/BCC 	$9Q###	v155_ $

d 8H 	8-!8!8 	89Q 6777i(yC   s   =N &OO  c                     |||d}t          | ||f|fi |}	|r|	d         |	d         |	d         |	d         fS |	d         S )a	  Bounded minimization for scalar functions.

    Parameters
    ----------
    func : callable f(x,*args)
        Objective function to be minimized (must accept and return scalars).
    x1, x2 : float or array scalar
        Finite optimization bounds.
    args : tuple, optional
        Extra arguments passed to function.
    xtol : float, optional
        The convergence tolerance.
    maxfun : int, optional
        Maximum number of function evaluations allowed.
    full_output : bool, optional
        If True, return optional outputs.
    disp: int, optional
        If non-zero, print messages.

        ``0`` : no message printing.

        ``1`` : non-convergence notification messages only.

        ``2`` : print a message on convergence too.

        ``3`` : print iteration results.

    Returns
    -------
    xopt : ndarray
        Parameters (over given interval) which minimize the
        objective function.
    fval : number
        (Optional output) The function value evaluated at the minimizer.
    ierr : int
        (Optional output) An error flag (0 if converged, 1 if maximum number of
        function calls reached).
    numfunc : int
        (Optional output) The number of function calls made.

    See also
    --------
    minimize_scalar: Interface to minimization algorithms for scalar
        univariate functions. See the 'Bounded' `method` in particular.

    Notes
    -----
    Finds a local minimizer of the scalar function `func` in the
    interval x1 < xopt < x2 using Brent's method. (See `brent`
    for auto-bracketing.)

    References
    ----------
    .. [1] Forsythe, G.E., M. A. Malcolm, and C. B. Moler. "Computer Methods
           for Mathematical Computations." Prentice-Hall Series in Automatic
           Computation 259 (1977).
    .. [2] Brent, Richard P. Algorithms for Minimization Without Derivatives.
           Courier Corporation, 2013.

    Examples
    --------
    `fminbound` finds the minimizer of the function in the given range.
    The following examples illustrate this.

    >>> from scipy import optimize
    >>> def f(x):
    ...     return (x-1)**2
    >>> minimizer = optimize.fminbound(f, -4, 4)
    >>> minimizer
    1.0
    >>> minimum = f(minimizer)
    >>> minimum
    0.0
    >>> res = optimize.fminbound(f, 3, 4, full_output=True)
    >>> minimizer, fval, ierr, numfunc = res
    >>> minimizer
    3.000005960860986
    >>> minimum = f(minimizer)
    >>> minimum, fval
    (4.000023843479476, 4.000023843479476)
    )r   r2   r   r=   r:   r   r   )_minimize_scalar_bounded)
r   x1x2rF   r   r   r   r   optionsr[   s
             r?   r   r   m  si    f   G #4"b4
C
C7
C
CC 3xUS]CK??3xrA   c           	      v   t          |           |}t          |          dk    rt          d          |\  }}	t          |          rt          |	          st          d          ||	k    rt          d          d}
d}d}t	          d          }d	d
t	          d          z
  z  }||	}}||||z
  z  z   }||}}dx}}|} | |g|R  }d}d||f}t
          j        }|x}}d	||z   z  }|t          j        |          z  |d
z  z   }d|z  }|dk    r4t          d           t          |           t          d||fz   z             t          j        ||z
            |d	||z
  z  z
  k    r;d} t          j        |          |k    rd} ||z
  ||z
  z  }!||z
  ||z
  z  }"||z
  |"z  ||z
  |!z  z
  }#d|"|!z
  z  }"|"dk    r|# }#t          j        |"          }"|}!|}t          j        |#          t          j        d	|"z  |!z            k     r`|#|"||z
  z  k    rT|#|"||z
  z  k     rH|#dz   |"z  }||z   }d}||z
  |k     s	||z
  |k     r&t          j	        ||z
            ||z
  dk    z   }$||$z  }nd} | r||k    r||z
  }n||z
  }||z  }d}t          j	        |          |dk    z   }$||$t          j
        t          j        |          |          z  z   } | |g|R  }|dz  }|||f}|dk    rt          d||fz   z             ||k    r||k    r|}n|}||}}||}}||}}n6||k     r|}n|}||k    s||k    r	||}}||}}n||k    s||k    s||k    r||}}d	||z   z  }|t          j        |          z  |d
z  z   }d|z  }||k    rd}
n%t          j        ||z
            |d	||z
  z  z
  k    ;t          j        |          s(t          j        |          st          j        |          rd}
|}%|dk    rt          ||
|%|||           t          |%|
|
dk    ddt          d         d                    |
d          |||          }&|&S )a  
    Options
    -------
    maxiter : int
        Maximum number of iterations to perform.
    disp: int, optional
        If non-zero, print messages.

        ``0`` : no message printing.

        ``1`` : non-convergence notification messages only.

        ``2`` : print a message on convergence too.

        ``3`` : print iteration results.

    xatol : float
        Absolute error in solution `xopt` acceptable for convergence.

    r   zbounds must have two elements.z+Optimization bounds must be finite scalars.z(The lower bound exceeds the upper bound.r   z2 Func-count     x          f(x)          Procedurez       initialgOd@<r   g      @g      @r{  r!   r    z%5.0f   %12.6g %12.6g %sz       parabolicz       goldenzSolution found.z)Maximum number of function calls reached.r4   )r   r!   r   r  )r:   r   r0   r   r=   r   r   )r   r  ru   r   r   rC   r   r   r  signmaximumr  	_endprintr   r  get)'r   r   rF   r   r2   r   r   r   r  r  flagheaderrL  sqrt_epsgolden_meanar  fulcnfcxfratr   r=   r   num	fmin_datafuffulcfnfcr   tol1tol2r	   r   qr   sir6  r8  s'                                          r?   r  r    sS   . ?+++F
6{{a9:::FBR   H%5b%9%9 HFGGG	BwwCDDDDAFDG}}HtCyy)KrqA{a!e$$DDCMC!
A	a$B
CBI	BED	ABbfRjj 53;.D:Daxxc


f(I,?@AAA6"r'??dSAE]2336!99tFcb5j)AdrDy)Ada28q.0Aq1uA3wwBq		AAA RVCE!G__,,1q!b&z>>a"f%%3w!mH)UdNNQ$b))b2g!^<B)C 	#RxxFFa-C"DWS\\SAX&bjd3333T!^d^^^q!RL	!88,	TG0CDEEE88Bwwt%DBCBB2vvd

r		!4erT++42::43;;eAE]"&**$us{2Tz&==DK 6"r'??dSAE]233N 
x|| rx|| rx|| Daxx!T4555TDAI(9)3(7(>%@ %@ ADD" s5 5 5F MrA   c                   6    e Zd Z	 	 ddZddZd Zd	 ZddZdS )BrentrR   `sbO>r  r   c                     || _         || _        || _        || _        d| _        d| _        d | _        d | _        d| _        d| _	        || _
        d S )Ngdy=gŋ!r?r   )r   rF   tolr2   _mintol_cgxminr6  iterfuncallsr   )r>   r   rF   r  r2   r   r   s          r?   r@   zBrent.__init__c	  sS    								rA   Nc                     || _         d S r9   )brack)r>   r  s     r?   set_bracketzBrent.set_bracketr	  s    


rA   c                    | j         }| j        }| j        }|t          ||          \  }}}}}}	}
nt	          |          dk    r(t          ||d         |d         |          \  }}}}}}	}
nt	          |          dk    rd|\  }}}||k    r||}}||k     r||k     st          d           ||f|z    } ||f|z    } ||f|z    }	||k     r||	k     st          d          d}
nt          d	          ||||||	|
fS )
NrF   r   r   r!   xaxbrF   r   WBracketing values (xa, xb, xc) do not fulfill this requirement: (xa < xb) and (xb < xc)cBracketing values (xa, xb, xc) do not fulfill this requirement: (f(xb) < f(xa)) and (f(xb) < f(xc))3Bracketing interval must be length 2 or 3 sequence.)r   rF   r  r
   r  ru   )r>   r   rF   r  r  r  r1  fafbr  r  s              r?   get_bracket_infozBrent.get_bracket_infou	  sv   yy
 =/6t$/G/G/G,BBBHHZZ1__/6ta:?(0O 0O 0O,BBBHHZZ1__JBBRRB"WW277 I   &B&B&B"WW277 M  
 HH 7 8 8 8 2r2r2x//rA   c                    | j         }|                                 \  }}}}}}}| j        }	| j        }
|x}x}}|x}x}}||k     r|}|}n|}|}d}d}| j        dk    rCt          d           t          dddddddd	           t          |d
d|dd|d           || j        k     r*| j        t          j	        |          z  |	z   }d|z  }d||z   z  }t          j	        ||z
            |d||z
  z  z
  k     rnt          j	        |          |k    r||k    r||z
  }n||z
  }|
|z  }n||z
  ||z
  z  }||z
  ||z
  z  }||z
  |z  ||z
  |z  z
  }d||z
  z  }|dk    r| }t          j	        |          }|}|}||||z
  z  k    rk||||z
  z  k     r_t          j	        |          t          j	        d|z  |z            k     r/|dz  |z  }||z   }||z
  |k     s	||z
  |k     r||z
  dk    r|}n| }n||k    r||z
  }n||z
  }|
|z  }t          j	        |          |k     r|dk    r||z   }n||z
  }n||z   } ||f| j
        z    }|dz  }||k    r7||k     r|}n|}||k    s||k    r	|}|}|}|}n.||k    s||k    s||k    r|}|}n||k    r|}n|}|}|}|}|}|}|}| j        dk    rt          |d
d|dd|d           |dz  }|| j        k     *|| _        || _        || _        || _        d S )Nr{  r   r   r  
Func-count^12r=   f(x) ^12^12g^12.6gr   r   r   r!   )r   r  r  r  r   r  r2   r  rC   r   rF   r  r6  r  r  )r>   r   r  r  r1  r  r  r  r  r  r  r=   rD  rE  fwfvr   r  r  deltaxr  r  r  xmidr  tmp1tmp2r   dx_tempur  s                                  r?   optimizezBrent.optimize	  s(   y+/+@+@+B+B(BBB,h AR"GGAAAAA9q==#JJJ\??????&???@@@X;;;Q;;;;;;<<<dl""8bfQii''1D:D!a%=Dva$h4#Q-#788 v$&&IIUFFUFFlA"r'*A"r'*UdNa!et^3dTk*3JJAvd|| Q''a$!a%..@.@RVC$J,@%A%AAAc'D.CCAQ$1q5D..!8q=="&CC#'%CT		!"Q!"Q,Csd""!88DAADAAGty(*BMHREEAAA"HH!q&&AABBBBhhAFFQABFFAAAy1}}??????B???@@@AIDc dl""l 			 rA   Fc                 H    |r| j         | j        | j        | j        fS | j         S r9   )r  r6  r  r  )r>   r   s     r?   
get_resultzBrent.get_result
  s)     	9diDMAA9rA   )rR   r  r  r   r   r9   )F)rN   rO   rP   r@   r  r  r  r  rR   rA   r?   r  r  a	  sy        ;>%&      $0 $0 $0Lr! r! r!h     rA   r  r  c                 z    ||d}t          | ||fi |}|r|d         |d         |d         |d         fS |d         S )a  
    Given a function of one variable and a possible bracket, return
    a local minimizer of the function isolated to a fractional precision
    of tol.

    Parameters
    ----------
    func : callable f(x,*args)
        Objective function.
    args : tuple, optional
        Additional arguments (if present).
    brack : tuple, optional
        Either a triple ``(xa, xb, xc)`` satisfying ``xa < xb < xc`` and
        ``func(xb) < func(xa) and  func(xb) < func(xc)``, or a pair
        ``(xa, xb)`` to be used as initial points for a downhill bracket search
        (see `scipy.optimize.bracket`).
        The minimizer ``x`` will not necessarily satisfy ``xa <= x <= xb``.
    tol : float, optional
        Relative error in solution `xopt` acceptable for convergence.
    full_output : bool, optional
        If True, return all output args (xmin, fval, iter,
        funcalls).
    maxiter : int, optional
        Maximum number of iterations in solution.

    Returns
    -------
    xmin : ndarray
        Optimum point.
    fval : float
        (Optional output) Optimum function value.
    iter : int
        (Optional output) Number of iterations.
    funcalls : int
        (Optional output) Number of objective function evaluations made.

    See also
    --------
    minimize_scalar: Interface to minimization algorithms for scalar
        univariate functions. See the 'Brent' `method` in particular.

    Notes
    -----
    Uses inverse parabolic interpolation when possible to speed up
    convergence of golden section method.

    Does not ensure that the minimum lies in the range specified by
    `brack`. See `scipy.optimize.fminbound`.

    Examples
    --------
    We illustrate the behaviour of the function when `brack` is of
    size 2 and 3 respectively. In the case where `brack` is of the
    form ``(xa, xb)``, we can see for the given values, the output does
    not necessarily lie in the range ``(xa, xb)``.

    >>> def f(x):
    ...     return (x-1)**2

    >>> from scipy import optimize

    >>> minimizer = optimize.brent(f, brack=(1, 2))
    >>> minimizer
    1
    >>> res = optimize.brent(f, brack=(-1, 0.5, 2), full_output=True)
    >>> xmin, fval, iter, funcalls = res
    >>> f(xmin), fval
    (0.0, 0.0)

    r   r2   r=   r:   r   r   )_minimize_scalar_brentr   rF   r  r  r   r2   r  r[   s           r?   r   r   
  s`    N !# #G
 ud
>
>g
>
>C 3xUSZV<<3xrA   c                 B   t          |           |}|dk     rt          d|          t          | ||d||          }|                    |           |                                 |                    d          \  }	}
}}||k     o(t          j        |	          pt          j        |
           }|rd| d}n>||k    rd}t          j        |	          st          j        |
          rt          d	          }|rt          | |           t          |
|	||||
          S )a:  
    Options
    -------
    maxiter : int
        Maximum number of iterations to perform.
    xtol : float
        Relative error in solution `xopt` acceptable for convergence.
    disp : int, optional
        If non-zero, print messages.

        ``0`` : no message printing.

        ``1`` : non-convergence notification messages only.

        ``2`` : print a message on convergence too.

        ``3`` : print iteration results.

    Notes
    -----
    Uses inverse parabolic interpolation when possible to speed up
    convergence of golden section method.

    r   ztolerance should be >= 0, got T)r   rF   r  r   r2   r   )r   k
Optimization terminated successfully;
The returned value satisfies the termination criteria
(using xtol =  )&
Maximum number of iterations exceededr4   )r:   r=   r   r   r0   r   )r   ru   r  r  r  r  rC   r  r  r  r   )r   r  rF   r   r2   r   r   r  r   r=   r6  r   r   r0   r   s                  r?   r  r  f
  sa   6 ?+++
C
QwwA#AABBBt$C"G$@ @ @E	e	NN))d);;AtS$GmCRXa[[%BBHTNN CG 2-$(- - - '>>?G8A;; 	2"(4.. 	2(/1G =&7{G<<<daSt")7< < < <rA   i  c                 l    ||d}t          | ||fi |}|r|d         |d         |d         fS |d         S )aF  
    Return the minimizer of a function of one variable using the golden section
    method.

    Given a function of one variable and a possible bracketing interval,
    return a minimizer of the function isolated to a fractional precision of
    tol.

    Parameters
    ----------
    func : callable func(x,*args)
        Objective function to minimize.
    args : tuple, optional
        Additional arguments (if present), passed to func.
    brack : tuple, optional
        Either a triple ``(xa, xb, xc)`` where ``xa < xb < xc`` and
        ``func(xb) < func(xa) and  func(xb) < func(xc)``, or a pair (xa, xb)
        to be used as initial points for a downhill bracket search (see
        `scipy.optimize.bracket`).
        The minimizer ``x`` will not necessarily satisfy ``xa <= x <= xb``.
    tol : float, optional
        x tolerance stop criterion
    full_output : bool, optional
        If True, return optional outputs.
    maxiter : int
        Maximum number of iterations to perform.

    Returns
    -------
    xmin : ndarray
        Optimum point.
    fval : float
        (Optional output) Optimum function value.
    funcalls : int
        (Optional output) Number of objective function evaluations made.

    See also
    --------
    minimize_scalar: Interface to minimization algorithms for scalar
        univariate functions. See the 'Golden' `method` in particular.

    Notes
    -----
    Uses analog of bisection method to decrease the bracketed
    interval.

    Examples
    --------
    We illustrate the behaviour of the function when `brack` is of
    size 2 and 3, respectively. In the case where `brack` is of the
    form (xa,xb), we can see for the given values, the output need
    not necessarily lie in the range ``(xa, xb)``.

    >>> def f(x):
    ...     return (x-1)**2

    >>> from scipy import optimize

    >>> minimizer = optimize.golden(f, brack=(1, 2))
    >>> minimizer
    1
    >>> res = optimize.golden(f, brack=(-1, 0.5, 2), full_output=True)
    >>> xmin, fval, funcalls = res
    >>> f(xmin), fval
    (9.925165290385052e-18, 9.925165290385052e-18)

    r  r=   r:   r   )_minimize_scalar_goldenr  s           r?   r	   r	   
  sU    J w//G
!$t
?
?w
?
?C 3xUS[003xrA   c           	         t          |           |}|t          | |          \  }}	}
}}}}nt          |          dk    r(t          | |d         |d         |          \  }}	}
}}}}nt          |          dk    rd|\  }}	}
||
k    r||
}}
||	k     r|	|
k     st          d           | |f|z    } | |	f|z    } | |
f|z    }||k     r||k     st          d	          d}nt          d
          d}d|z
  }|
}|}t	          j        |
|	z
            t	          j        |	|z
            k    r|	}|	||
|	z
  z  z   }n|	}|	||	|z
  z  z
  } | |f|z    } | |f|z    }|dz  }d}|dk    r)t          d           t          dddddddd           t          |          D ]}t	          j        ||z
            |t	          j        |          t	          j        |          z   z  k    r nu||k     r|}|}||z  ||z  z   }|} | |f|z    }n|}|}||z  ||z  z   }|} | |f|z    }|dz  }|dk    r)||k     r||}}n||}}t          |dd|dd|d           |dz  }||k     r|}|}n|}|}||k     o(t	          j        |          pt	          j        |           }|rd| d}n>||k    rd}t	          j        |          st	          j        |          rt          d          }|rt          | |           t          ||||||          S )a  
    Options
    -------
    xtol : float
        Relative error in solution `xopt` acceptable for convergence.
    maxiter : int
        Maximum number of iterations to perform.
    disp: int, optional
        If non-zero, print messages.

        ``0`` : no message printing.

        ``1`` : non-convergence notification messages only.

        ``2`` : print a message on convergence too.

        ``3`` : print iteration results.
    Nr  r   r   r!   r  r   r  r  r  gz7?r   r  r  r  r=   r  r  r  r  r  r  r  r4   r:   r   r=   r   r0   r   )r   r
   r  ru   rC   r   r  r  r  r  r  r   )r   r  rF   r   r2   r   r   r  r  r  r1  r  r  r  r  _gR_gCx3r   r  r  rU  rV  r   r  r  r6  r0   r   s                                r?   r  r  
  s:   * ?+++
C}+24d+C+C+C(BBB	Uq+24E!H6;AhT,K ,K ,K(BBB	Uq
BGGBbrBwwE   TREDL"TREDL"TREDL"brBwwI   NOOO
C
)C	B	B
rBw"&b//))#b/!#b/!		B		BMH
Caxxc


;;;C;;;f;;;<<<7^^  6"r'??cRVBZZ"&**%<===EGGBBrC"H$BB&BBBBrC"H$BB&BA!88RddX@@@T@@@4@@@AAAq 	RGmFRXd^^%Erx~~ FG 2-$(- - - '>>?G8D>> 	2RXd^^ 	2(/1G =&7{G<<<dTs")7< < < <rA   r{  r        [@  c                    d}d}t          j        ||g          \  }} | |f|z    } | |f|z    }	||	k     r||}}|	|}	}||||z
  z  z   }
 | |
f|z    }d}d}||	k     r^||z
  |	|z
  z  }||
z
  |	|z
  z  }||z
  }t          j        |          |k     rd|z  }nd|z  }|||
z
  |z  ||z
  |z  z
  |z  z
  }|||
|z
  z  z   }d}||k    rt          |          |dz  }||
z
  ||z
  z  dk    rB | |f|z    }|dz  }||k     r	|}|}|	}|}	n||	k    r|}
|}n|
||
|z
  z  z   } | |f|z    }|dz  }n~||z
  ||
z
  z  dk    r|} | |f|z    }|dz  }n^||z
  |
|z
  z  dk    r6 | |f|z    }|dz  }||k     r!|
}|}
|
||
|z
  z  z   }|}	|} | |f|z    }|dz  }n|
||
|z
  z  z   } | |f|z    }|dz  }|}|
}|}
|	}|}	|}||	k     ^|	|k     r|	|k    p|	|k     o|	|k    }||cxk     o|
k     nc p|
|cxk     o|k     nc }t          j        |          o't          j        |          ot          j        |
          }d	}|r|r|st          |          }|||
||	||f|_        ||||
||	||fS )
u
  
    Bracket the minimum of a function.

    Given a function and distinct initial points, search in the
    downhill direction (as defined by the initial points) and return
    three points that bracket the minimum of the function.

    Parameters
    ----------
    func : callable f(x,*args)
        Objective function to minimize.
    xa, xb : float, optional
        Initial points. Defaults `xa` to 0.0, and `xb` to 1.0.
        A local minimum need not be contained within this interval.
    args : tuple, optional
        Additional arguments (if present), passed to `func`.
    grow_limit : float, optional
        Maximum grow limit.  Defaults to 110.0
    maxiter : int, optional
        Maximum number of iterations to perform. Defaults to 1000.

    Returns
    -------
    xa, xb, xc : float
        Final points of the bracket.
    fa, fb, fc : float
        Objective function values at the bracket points.
    funcalls : int
        Number of function evaluations made.

    Raises
    ------
    BracketError
        If no valid bracket is found before the algorithm terminates.
        See notes for conditions of a valid bracket.

    Notes
    -----
    The algorithm attempts to find three strictly ordered points (i.e.
    :math:`x_a < x_b < x_c` or :math:`x_c < x_b < x_a`) satisfying
    :math:`f(x_b) ≤ f(x_a)` and :math:`f(x_b) ≤ f(x_c)`, where one of the
    inequalities must be satisfied strictly and all :math:`x_i` must be
    finite.

    Examples
    --------
    This function can find a downward convex region of a function:

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.optimize import bracket
    >>> def f(x):
    ...     return 10*x**2 + 3*x + 5
    >>> x = np.linspace(-2, 2)
    >>> y = f(x)
    >>> init_xa, init_xb = 0.1, 1
    >>> xa, xb, xc, fa, fb, fc, funcalls = bracket(f, xa=init_xa, xb=init_xb)
    >>> plt.axvline(x=init_xa, color="k", linestyle="--")
    >>> plt.axvline(x=init_xb, color="k", linestyle="--")
    >>> plt.plot(x, y, "-k")
    >>> plt.plot(xa, fa, "bx")
    >>> plt.plot(xb, fb, "rx")
    >>> plt.plot(xc, fc, "bx")
    >>> plt.show()

    Note that both initial points were to the right of the minimum, and the
    third point was found in the "downhill" direction: the direction
    in which the function appeared to be decreasing (to the left).
    The final points are strictly ordered, and the function value
    at the middle point is less than the function values at the endpoints;
    it follows that a minimum must lie within the bracket.

    gw?gO
;r   r   r   zNo valid bracket was found before the iteration limit was reached. Consider trying different initial points or increasing `maxiter`.r!   r{  zcThe algorithm terminated without finding a valid bracket. Consider trying different initial points.)rC   r   r   RuntimeErrorr   BracketErrordata)r   r  r  rF   
grow_limitr2   _gold_verysmall_numr  r  r1  r  r  r  r  r  valdenomrD  wlimr   r  cond1cond2cond3r   s                             r?   r
   r
   d  s   T ENZR!!FB	ut|	B	ut|	B
RRBRB	erBw	B		BHD77RBG$RBG$Tk6#;;''.(EE#IE27d"b2g%55>>J"r'**' '>>s###	FrAv$$t%BMHRr''Ub2g&&At%BMHH$h#s**At%BMHH$ha 3&&t%BMHR"r'**TQD4K)AUb2g&&At%BMHq 77v "W!r<rBw';28E"\\\\r\\\\)R"\\\\r\\\\EKOOCBCBKOOE7C e  b"b"b(3r2r2r8++rA   c                       e Zd ZdS )r%  Nro   rR   rA   r?   r%  r%    rp   rA   r%  c           	         	  | |||fi |}n# t           $ r}t          |          }|j        \  }}	}
}}}}||	|
g|||g}}t          j        t          j        ||g                    rt          j        t          j        }}n$t          j        |          }||         ||         }}t          |||dd|          cY d }~S d }~ww xY w|S )Nr   Fr  )	r%  r~   r&  rC   r   r  r4   r   r   )solverr:   r
   rF   r  r[   r   r   r  r  r1  r  r  r  r  xsfsr=   imins                      r?   _recover_from_bracket_errorr6    s   $AfS'433733 
A 
A 
A!ff+,6(BBBb"B|B6"(B8$$%% 	(VRVsAA9R==DXr$xsA#H"#UCA A A 	A 	A 	A 	A 	A 	A
A Js    
CB!B?9C?Cc                    |                                 \  }||         ||         }}| |         ||         }} || z
  |z  }|| z
  |z  }|dk    }t          j        ||d          }t          j        |d|          }	t          j        ||d          }
t          j        |d|          }t          j        ||	z             }t          j        |
|z             }||k    r||fndS )a  
    Given a parameter vector ``x0`` with length ``n`` and a direction
    vector ``alpha`` with length ``n``, and lower and upper bounds on
    each of the ``n`` parameters, what are the bounds on a scalar
    ``l`` such that ``lower_bound <= x0 + alpha * l <= upper_bound``.


    Parameters
    ----------
    x0 : np.array.
        The vector representing the current location.
        Note ``np.shape(x0) == (n,)``.
    alpha : np.array.
        The vector representing the direction.
        Note ``np.shape(alpha) == (n,)``.
    lower_bound : np.array.
        The lower bounds for each parameter in ``x0``. If the ``i``th
        parameter in ``x0`` is unbounded below, then ``lower_bound[i]``
        should be ``-np.inf``.
        Note ``np.shape(lower_bound) == (n,)``.
    upper_bound : np.array.
        The upper bounds for each parameter in ``x0``. If the ``i``th
        parameter in ``x0`` is unbounded above, then ``upper_bound[i]``
        should be ``np.inf``.
        Note ``np.shape(upper_bound) == (n,)``.

    Returns
    -------
    res : tuple ``(lmin, lmax)``
        The bounds for ``l`` such that
            ``lower_bound[i] <= x0[i] + alpha[i] * l <= upper_bound[i]``
        for all ``i``.

    r   )r   r   )nonzerorC   r
  r  r  )r   r  r  r   r8  lowhighposlmin_poslmin_neglmax_poslmax_neglminlmaxs                 r?   _line_for_searchrB  )  s    L }}HG*73[5IK7U7^Bu
$C"%D !)CxS!$$HxQ%%HxT1%%HxQ$$H6(X%&&D6(X%&&D  4<<D$<<V3rA   MbP?c                 P     fdt          j                  s||fn            fS |B|@t          t          dt	                      |          }|j        |j        }	}|z  |	z   fS t          ||          }
t          j        |
d                   r.t          j	        |
d                   rt           ||          S t          j        |
d                   sFt          j	        |
d                   s,t          |
|dz            }|j        z  |j        z   fS t          j        |
d                   t          j        |
d                   f}
t          fd	|
|dz            }t          j        |j                  z  |j        z   fS )
a  Line-search algorithm using fminbound.

    Find the minimum of the function ``func(x0 + alpha*direc)``.

    lower_bound : np.array.
        The lower bounds for each parameter in ``x0``. If the ``i``th
        parameter in ``x0`` is unbounded below, then ``lower_bound[i]``
        should be ``-np.inf``.
        Note ``np.shape(lower_bound) == (n,)``.
    upper_bound : np.array.
        The upper bounds for each parameter in ``x0``. If the ``i``th
        parameter in ``x0`` is unbounded above, then ``upper_bound[i]``
        should be ``np.inf``.
        Note ``np.shape(upper_bound) == (n,)``.
    fval : number.
        ``fval`` is equal to ``func(p)``, the idea is just to avoid
        recomputing it so we can limit the ``fevals``.

    c                 &     | z  z             S r9   rR   )r  r   r   xis    r?   myfuncz"_linesearch_powell.<locals>.myfunc}  s    tAbL!!!rA   N)r   r   r!   )r6  r  d   )r   c                 >     t          j        |                     S r9   )rC   tan)r=   rG  s    r?   <lambda>z$_linesearch_powell.<locals>.<lambda>  s    &&++ rA   )rC   r   r6  r  tupler=   r:   rB  isneginfisposinf_linesearch_powellr  arctanrJ  )r   r   rF  r  r  r   r6  r[   	alpha_minfretboundrG  s   ```        @r?   rO  rO  h  s   *" " " " " " " 6":: '!%!1q"QB7GH		!4)*@*0$cK K K%4	^QVR B[AA;uQx   	'R[q%:%: 	'%dAr#FFFFU1X&& 	'r{58/D/D 	'*65c	JJJCB7AFB&&
 IeAh''58)<)<<E*++++Ci! ! !C #B7AFB&&rA   c                    |||||||	d}t          |
          }
t          | ||fd|
i|}|r<|d         |d         |d         |d         |d         |d         f}|	r||d	         fz  }|S |	r|d         |d	         fS |d         S )
a  
    Minimize a function using modified Powell's method.

    This method only uses function values, not derivatives.

    Parameters
    ----------
    func : callable f(x,*args)
        Objective function to be minimized.
    x0 : ndarray
        Initial guess.
    args : tuple, optional
        Extra arguments passed to func.
    xtol : float, optional
        Line-search error tolerance.
    ftol : float, optional
        Relative error in ``func(xopt)`` acceptable for convergence.
    maxiter : int, optional
        Maximum number of iterations to perform.
    maxfun : int, optional
        Maximum number of function evaluations to make.
    full_output : bool, optional
        If True, ``fopt``, ``xi``, ``direc``, ``iter``, ``funcalls``, and
        ``warnflag`` are returned.
    disp : bool, optional
        If True, print convergence messages.
    retall : bool, optional
        If True, return a list of the solution at each iteration.
    callback : callable, optional
        An optional user-supplied function, called after each
        iteration.  Called as ``callback(xk)``, where ``xk`` is the
        current parameter vector.
    direc : ndarray, optional
        Initial fitting step and parameter order set as an (N, N) array, where N
        is the number of fitting parameters in `x0`. Defaults to step size 1.0
        fitting all parameters simultaneously (``np.eye((N, N))``). To
        prevent initial consideration of values in a step or to change initial
        step size, set to 0 or desired step size in the Jth position in the Mth
        block, where J is the position in `x0` and M is the desired evaluation
        step, with steps being evaluated in index order. Step size and ordering
        will change freely as minimization proceeds.

    Returns
    -------
    xopt : ndarray
        Parameter which minimizes `func`.
    fopt : number
        Value of function at minimum: ``fopt = func(xopt)``.
    direc : ndarray
        Current direction set.
    iter : int
        Number of iterations.
    funcalls : int
        Number of function calls made.
    warnflag : int
        Integer warning flag:
            1 : Maximum number of function evaluations.
            2 : Maximum number of iterations.
            3 : NaN result encountered.
            4 : The result is out of the provided bounds.
    allvecs : list
        List of solutions at each iteration.

    See also
    --------
    minimize: Interface to unconstrained minimization algorithms for
        multivariate functions. See the 'Powell' method in particular.

    Notes
    -----
    Uses a modification of Powell's method to find the minimum of
    a function of N variables. Powell's method is a conjugate
    direction method.

    The algorithm has two loops. The outer loop merely iterates over the inner
    loop. The inner loop minimizes over each current direction in the direction
    set. At the end of the inner loop, if certain conditions are met, the
    direction that gave the largest decrease is dropped and replaced with the
    difference between the current estimated x and the estimated x from the
    beginning of the inner-loop.

    The technical conditions for replacing the direction of greatest
    increase amount to checking that

    1. No further gain can be made along the direction of greatest increase
       from that iteration.
    2. The direction of greatest increase accounted for a large sufficient
       fraction of the decrease in the function value from that iteration of
       the inner loop.

    References
    ----------
    Powell M.J.D. (1964) An efficient method for finding the minimum of a
    function of several variables without calculating derivatives,
    Computer Journal, 7 (2):155-162.

    Press W., Teukolsky S.A., Vetterling W.T., and Flannery B.P.:
    Numerical Recipes (any edition), Cambridge University Press

    Examples
    --------
    >>> def f(x):
    ...     return x**2

    >>> from scipy import optimize

    >>> minimum = optimize.fmin_powell(f, -1)
    Optimization terminated successfully.
             Current function value: 0.000000
             Iterations: 2
             Function evaluations: 16
    >>> minimum
    array(0.0)

    )r   r   r2   r1   r   direcr   r\   r=   r:   rU  r   r   r   r   )rl   _minimize_powell)r   r   rF   r   r   r2   r   r   r   r   r\   rU  r   r[   r   s                  r?   r   r     s    l  " "D h''H
4T
E
EH
E
E
EC 
s8SZWs5zv;H/ 	*I))G 	s8S^++s8OrA   c           
      	   t          |           |}|}t          |                                          }|r|g}t          |          }|||dz  }|dz  }nI|#|t          j        k    r|dz  }n1t          j        }n$|"|t          j        k    r|dz  }nt          j        }t          | ||          \  }} |
t          |t                    }
n`t          |
t                    }
t          j	        
                    |
          |
j        d         k    rt          j        dt          d           |d\  }}nZ|j        |j        }}t	          j        ||k              st	          j        ||k              rt          j        d	t          d            | |          }|                                }d}	 	 |}d}d}t'          |          D ]9}|
|         }|}t)          | |||dz  |||          \  }}}||z
  |k    r||z
  }|}:|dz  }|r|                    |           t-          ||          }t/          ||          rn`|t	          j        |          t	          j        |          z   z  dz   }d||z
  z  |k    rn#|d         |k    rn||k    rnt	          j        |          rt	          j        |          rn||z
  }|                                }||d} nt5          ||||          \  }!} |t7          | d          |z  z   }" | |"          }||k    rud||z   d|z  z
  z  }#||z
  |z
  }$|#|$|$z  z  }#||z
  }$|#||$z  |$z  z  }#|#dk     rAt)          | |||dz  |||          \  }}}t	          j        |          r|
d         |
|<   ||
d<   n# t8          $ r Y nw xY wd}%t:          d         }&|r@t	          j        ||k              st	          j        ||k              rd}%t:          d         }&n{|d         |k    rd}%t:          d         }&n_||k    rd}%t:          d         }&nIt	          j        |          s&t	          j        |                                          rd}%t:          d         }&|	rSt=          |%|&t>                     tA          d|d           tA          d|z             tA          d|d         z             t-          ||
||d         |%|%dk    |&|          }'|r||'d<   |'S ) a  
    Minimization of scalar function of one or more variables using the
    modified Powell algorithm.

    Parameters
    ----------
    fun : callable
        The objective function to be minimized::

            fun(x, *args) -> float

        where ``x`` is a 1-D array with shape (n,) and ``args``
        is a tuple of the fixed parameters needed to completely
        specify the function.
    x0 : ndarray, shape (n,)
        Initial guess. Array of real elements of size (n,),
        where ``n`` is the number of independent variables.
    args : tuple, optional
        Extra arguments passed to the objective function and its
        derivatives (`fun`, `jac` and `hess` functions).
    method : str or callable, optional
        The present documentation is specific to ``method='powell'``, but other
        options are available. See documentation for `scipy.optimize.minimize`.
    bounds : sequence or `Bounds`, optional
        Bounds on decision variables. There are two ways to specify the bounds:

        1. Instance of `Bounds` class.
        2. Sequence of ``(min, max)`` pairs for each element in `x`. None
           is used to specify no bound.

        If bounds are not provided, then an unbounded line search will be used.
        If bounds are provided and the initial guess is within the bounds, then
        every function evaluation throughout the minimization procedure will be
        within the bounds. If bounds are provided, the initial guess is outside
        the bounds, and `direc` is full rank (or left to default), then some
        function evaluations during the first iteration may be outside the
        bounds, but every function evaluation after the first iteration will be
        within the bounds. If `direc` is not full rank, then some parameters
        may not be optimized and the solution is not guaranteed to be within
        the bounds.

    options : dict, optional
        A dictionary of solver options. All methods accept the following
        generic options:

        maxiter : int
            Maximum number of iterations to perform. Depending on the
            method each iteration may use several function evaluations.
        disp : bool
            Set to True to print convergence messages.

        See method-specific options for ``method='powell'`` below.
    callback : callable, optional
        Called after each iteration. The signature is::

            callback(xk)

        where ``xk`` is the current parameter vector.

    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. See
        `OptimizeResult` for a description of other attributes.

    Options
    -------
    disp : bool
        Set to True to print convergence messages.
    xtol : float
        Relative error in solution `xopt` acceptable for convergence.
    ftol : float
        Relative error in ``fun(xopt)`` acceptable for convergence.
    maxiter, maxfev : int
        Maximum allowed number of iterations and function evaluations.
        Will default to ``N*1000``, where ``N`` is the number of
        variables, if neither `maxiter` or `maxfev` is set. If both
        `maxiter` and `maxfev` are set, minimization will stop at the
        first reached.
    direc : ndarray
        Initial set of direction vectors for the Powell method.
    return_all : bool, optional
        Set to True to return a list of the best solution at each of the
        iterations.
    Nr"  r   r   zBdirec input is not full rank, some parameters may not be optimizedr   rz   )NNr   Tr{  rH  )r  r  r   r6  r!   r   g#B;r   r   r0   ry   r5   r1   r   r2   r4   r   r   r   r   )r:   rU  r   r   r   r0   r   r=   r   )!r   r   r   r  rC   r   r   r   r  r~  matrix_rankr   r   r   r   r  r  r   rE   r  rO  r  r   r*   r   r  rB  r  r   r  r  r   r  )(r   r   rF   r\   r   r   r   r2   r1   r   rU  r   r   r   r   r=   r   r!  r(  r  r   r6  r  r  r   biginddeltar  direc1fx2rX   bndrA  _r  ttempr7  r   r8  s(                                           r?   rV  rV  /  s   x ?+++FFA #AA6>d(T	 RV$hGGfGG	bfXFFVF ;4vNNLFD}AU###U+++9  ''5;q>99M -)a9 9 9 9 ~
 $. [[ $*9fi[6+"## 	9rvb;.>'?'? 	9ML)a9 9 9 9 477D	
BD>=	BFE1XX 
 
q"4T1f9=ALAL:>	#@ #@ #@a
 $J%''$JEFAID "q!!!"01$"?"?"?(3FGG "&**rvd||34u<Cb4i C''ayF""wx||   VFB"{':*1fk;OO4Sq\\F**B$r((CScCH,-T	E)T$YCxU4Z_$s77&8a 3J$/$/!' ' 'OD!V vf~~ +(-b	f$*b	  	 	 	E	{>@ H
)
$C
  %26+/** %bfQ_.E.E %o.	f		h'	i(	$ %28A;;??,, %e$ ?&xnEEE:$:::;;;'$.///1F1I=>>>Et&)#+h!m$'1. . .F  $#yMs2   3BN ;N >N N (N =CN 
NNc                     |dk    r|dk    rt          d|d           d S |dk    rd}n|dk    rdt          d          }t          ||           d S )	Nr   r!   r  )zO
Maximum number of function evaluations exceeded --- increase maxfun argument.
r   
r4   )r  r  r  )r=   r  r6  r   r   r   r   s          r?   r  r  !  sy    qyy!88 #$(#/ / / 	qyy-	+?5)++"4---
FrA   r  c           	      d   t          |          }|dk    rt          d          t          |          }	t          |          D ]q}
t	          |	|
         t
                    sTt          |	|
                   dk     r)t          |	|
                   t          |          fz   |	|
<   t          |	|
          |	|
<   r|dk    r|	d         }	t          j	        |	         }|j
        }|dk    r<t          j        ||d         t          j        |dd                   f          j        }t          j        |          s|f}t          | |          }t!          |          5 }t          j        t           |||                              }|dk    r|f}t          j        |          }n=|dk    r7t          j        ||dd                   }t          j        |j        |          }ddd           n# 1 swxY w Y   t          |          }t'          |                                d	          }t          j        |t,                    }t          j        |t.                    }t          |dz
  dd          D ]}
||
         }|||
         z  ||
<   ||z  }t          |          D ] }
||
         t          |                   ||
<   !|t          |                   }|dk    r|d         }|d         }t1          |          rt3          |          j        }t7                      }d
|v rd|d
<   d|v r||d<   nd|v rd|i|d<    || |fd|i|}t	          |t8                    r|j        }|j        }|j        }n|d         }|d         }|d         dk    }|s|rtA          j!        dtD          d           |r||||fS |S )a  Minimize a function over a given range by brute force.

    Uses the "brute force" method, i.e., computes the function's value
    at each point of a multidimensional grid of points, to find the global
    minimum of the function.

    The function is evaluated everywhere in the range with the datatype of the
    first call to the function, as enforced by the ``vectorize`` NumPy
    function. The value and type of the function evaluation returned when
    ``full_output=True`` are affected in addition by the ``finish`` argument
    (see Notes).

    The brute force approach is inefficient because the number of grid points
    increases exponentially - the number of grid points to evaluate is
    ``Ns ** len(x)``. Consequently, even with coarse grid spacing, even
    moderately sized problems can take a long time to run, and/or run into
    memory limitations.

    Parameters
    ----------
    func : callable
        The objective function to be minimized. Must be in the
        form ``f(x, *args)``, where ``x`` is the argument in
        the form of a 1-D array and ``args`` is a tuple of any
        additional fixed parameters needed to completely specify
        the function.
    ranges : tuple
        Each component of the `ranges` tuple must be either a
        "slice object" or a range tuple of the form ``(low, high)``.
        The program uses these to create the grid of points on which
        the objective function will be computed. See `Note 2` for
        more detail.
    args : tuple, optional
        Any additional fixed parameters needed to completely specify
        the function.
    Ns : int, optional
        Number of grid points along the axes, if not otherwise
        specified. See `Note2`.
    full_output : bool, optional
        If True, return the evaluation grid and the objective function's
        values on it.
    finish : callable, optional
        An optimization function that is called with the result of brute force
        minimization as initial guess. `finish` should take `func` and
        the initial guess as positional arguments, and take `args` as
        keyword arguments. It may additionally take `full_output`
        and/or `disp` as keyword arguments. Use None if no "polishing"
        function is to be used. See Notes for more details.
    disp : bool, optional
        Set to True to print convergence messages from the `finish` callable.
    workers : int or map-like callable, optional
        If `workers` is an int the grid is subdivided into `workers`
        sections and evaluated in parallel (uses
        `multiprocessing.Pool <multiprocessing>`).
        Supply `-1` to use all cores available to the Process.
        Alternatively supply a map-like callable, such as
        `multiprocessing.Pool.map` for evaluating the grid in parallel.
        This evaluation is carried out as ``workers(func, iterable)``.
        Requires that `func` be pickleable.

        .. versionadded:: 1.3.0

    Returns
    -------
    x0 : ndarray
        A 1-D array containing the coordinates of a point at which the
        objective function had its minimum value. (See `Note 1` for
        which point is returned.)
    fval : float
        Function value at the point `x0`. (Returned when `full_output` is
        True.)
    grid : tuple
        Representation of the evaluation grid. It has the same
        length as `x0`. (Returned when `full_output` is True.)
    Jout : ndarray
        Function values at each point of the evaluation
        grid, i.e., ``Jout = func(*grid)``. (Returned
        when `full_output` is True.)

    See Also
    --------
    basinhopping, differential_evolution

    Notes
    -----
    *Note 1*: The program finds the gridpoint at which the lowest value
    of the objective function occurs. If `finish` is None, that is the
    point returned. When the global minimum occurs within (or not very far
    outside) the grid's boundaries, and the grid is fine enough, that
    point will be in the neighborhood of the global minimum.

    However, users often employ some other optimization program to
    "polish" the gridpoint values, i.e., to seek a more precise
    (local) minimum near `brute's` best gridpoint.
    The `brute` function's `finish` option provides a convenient way to do
    that. Any polishing program used must take `brute's` output as its
    initial guess as a positional argument, and take `brute's` input values
    for `args` as keyword arguments, otherwise an error will be raised.
    It may additionally take `full_output` and/or `disp` as keyword arguments.

    `brute` assumes that the `finish` function returns either an
    `OptimizeResult` object or a tuple in the form:
    ``(xmin, Jmin, ... , statuscode)``, where ``xmin`` is the minimizing
    value of the argument, ``Jmin`` is the minimum value of the objective
    function, "..." may be some other returned values (which are not used
    by `brute`), and ``statuscode`` is the status code of the `finish` program.

    Note that when `finish` is not None, the values returned are those
    of the `finish` program, *not* the gridpoint ones. Consequently,
    while `brute` confines its search to the input grid points,
    the `finish` program's results usually will not coincide with any
    gridpoint, and may fall outside the grid's boundary. Thus, if a
    minimum only needs to be found over the provided grid points, make
    sure to pass in ``finish=None``.

    *Note 2*: The grid of points is a `numpy.mgrid` object.
    For `brute` the `ranges` and `Ns` inputs have the following effect.
    Each component of the `ranges` tuple can be either a slice object or a
    two-tuple giving a range of values, such as (0, 5). If the component is a
    slice object, `brute` uses it directly. If the component is a two-tuple
    range, `brute` internally converts it to a slice object that interpolates
    `Ns` points from its low-value to its high-value, inclusive.

    Examples
    --------
    We illustrate the use of `brute` to seek the global minimum of a function
    of two variables that is given as the sum of a positive-definite
    quadratic and two deep "Gaussian-shaped" craters. Specifically, define
    the objective function `f` as the sum of three other functions,
    ``f = f1 + f2 + f3``. We suppose each of these has a signature
    ``(z, *params)``, where ``z = (x, y)``,  and ``params`` and the functions
    are as defined below.

    >>> import numpy as np
    >>> params = (2, 3, 7, 8, 9, 10, 44, -1, 2, 26, 1, -2, 0.5)
    >>> def f1(z, *params):
    ...     x, y = z
    ...     a, b, c, d, e, f, g, h, i, j, k, l, scale = params
    ...     return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f)

    >>> def f2(z, *params):
    ...     x, y = z
    ...     a, b, c, d, e, f, g, h, i, j, k, l, scale = params
    ...     return (-g*np.exp(-((x-h)**2 + (y-i)**2) / scale))

    >>> def f3(z, *params):
    ...     x, y = z
    ...     a, b, c, d, e, f, g, h, i, j, k, l, scale = params
    ...     return (-j*np.exp(-((x-k)**2 + (y-l)**2) / scale))

    >>> def f(z, *params):
    ...     return f1(z, *params) + f2(z, *params) + f3(z, *params)

    Thus, the objective function may have local minima near the minimum
    of each of the three functions of which it is composed. To
    use `fmin` to polish its gridpoint result, we may then continue as
    follows:

    >>> rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25))
    >>> from scipy import optimize
    >>> resbrute = optimize.brute(f, rranges, args=params, full_output=True,
    ...                           finish=optimize.fmin)
    >>> resbrute[0]  # global minimum
    array([-1.05665192,  1.80834843])
    >>> resbrute[1]  # function value at global minimum
    -3.4085818767

    Note that if `finish` had been set to None, we would have gotten the
    gridpoint [-1.0 1.75] where the rounded function value is -2.892.

    (   z5Brute Force not possible with more than 40 variables.r   r!   r   N)poolr   r   r   r   r  rF   zhEither final optimization did not succeed or `finish` does not return `statuscode` as its last argument.r   rz   )#r  ru   r  r  r  slicerL  complexrC   mgridr   reshapeprodTiterable_Brute_Wrapperr'   r  r  r   r  r  r}  r  r   _getfullargspecrF   dictr   r=   r:   r0   r   r   r   )r   rangesrF   Nsr   finishr   workersr!  lranger#  grid
inpt_shapewrapped_funcmapperJoutNshapeindxNindxr  thisNJminfinish_argsfinish_kwargsr[   r0   s                             r?   r   r   3  s(   Z 	FA2vv . / / 	/&\\F1XX * *&)U++ 	*6!9~~!!!&),,~=q	vay)F1I	Q8FD J	Az$A
1220G0G HIIK;t w!$--L 
	!	!	! 2VxVVL$778899FF7D:d##DD!ee:dJqrrN33D:dfj11D2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 4[[F$**,,R(((DHQE8AuD1q5"b!!  q	&)#au}1XX ( (q'%,,'QeD	QAwAw <%f--2K''+,M-([  $(M&!!+%% )/~M)$ fT4<<d<m<<c>** 	#5D7DkGGq6Dq6D"glG 	< < S,< < < <  T4%%s   BG((G,/G,c                       e Zd ZdZd Zd ZdS )rn  zU
    Object to wrap user cost function for optimize.brute, allowing picklability
    c                 *    || _         |g n|| _        d S r9   )r   rF   )r>   r   rF   s      r?   r@   z_Brute_Wrapper.__init__=  s    ,BBD			rA   c                 p     | j         t          j        |                                          g| j        R  S r9   )r   rC   r   r   rF   )r>   r=   s     r?   rK   z_Brute_Wrapper.__call__A  s2    tvbjmm++--:	::::rA   N)rN   rO   rP   rQ   r@   rK   rR   rA   r?   rn  rn  8  s<         1 1 1; ; ; ; ;rA   rn  Tc           	      :   ddl }ddddddd	}| g d
}|                    t          dd                     |                    g d           |                    t          dd                     |                    g d           |                    t          dd                     |                    g d           |                    t          dd                     d                    |          }n|                                 } | |vrt          d|           |{g }||          D ]Z\  }}|                    d|z   ddt          |          z  z   dz   g           |                    t          | |d                     [d                    |          }n|                                }t          ||                    }||vrt          d|          ||         }|	                    d          }	d                    |	dd                   }
t          |
           t          t          j        |
         |	d                   }|j        }|(|                    |                                          }nd}|rt#          |           dS |S )a  
    Show documentation for additional options of optimization solvers.

    These are method-specific options that can be supplied through the
    ``options`` dict.

    Parameters
    ----------
    solver : str
        Type of optimization solver. One of 'minimize', 'minimize_scalar',
        'root', 'root_scalar', 'linprog', or 'quadratic_assignment'.
    method : str, optional
        If not given, shows all methods of the specified solver. Otherwise,
        show only the options for the specified method. Valid values
        corresponds to methods' names of respective solver (e.g., 'BFGS' for
        'minimize').
    disp : bool, optional
        Whether to print the result rather than returning it.

    Returns
    -------
    text
        Either None (for disp=True) or the text string (disp=False)

    Notes
    -----
    The solver-specific methods are:

    `scipy.optimize.minimize`

    - :ref:`Nelder-Mead <optimize.minimize-neldermead>`
    - :ref:`Powell      <optimize.minimize-powell>`
    - :ref:`CG          <optimize.minimize-cg>`
    - :ref:`BFGS        <optimize.minimize-bfgs>`
    - :ref:`Newton-CG   <optimize.minimize-newtoncg>`
    - :ref:`L-BFGS-B    <optimize.minimize-lbfgsb>`
    - :ref:`TNC         <optimize.minimize-tnc>`
    - :ref:`COBYLA      <optimize.minimize-cobyla>`
    - :ref:`COBYQA      <optimize.minimize-cobyqa>`
    - :ref:`SLSQP       <optimize.minimize-slsqp>`
    - :ref:`dogleg      <optimize.minimize-dogleg>`
    - :ref:`trust-ncg   <optimize.minimize-trustncg>`

    `scipy.optimize.root`

    - :ref:`hybr              <optimize.root-hybr>`
    - :ref:`lm                <optimize.root-lm>`
    - :ref:`broyden1          <optimize.root-broyden1>`
    - :ref:`broyden2          <optimize.root-broyden2>`
    - :ref:`anderson          <optimize.root-anderson>`
    - :ref:`linearmixing      <optimize.root-linearmixing>`
    - :ref:`diagbroyden       <optimize.root-diagbroyden>`
    - :ref:`excitingmixing    <optimize.root-excitingmixing>`
    - :ref:`krylov            <optimize.root-krylov>`
    - :ref:`df-sane           <optimize.root-dfsane>`

    `scipy.optimize.minimize_scalar`

    - :ref:`brent       <optimize.minimize_scalar-brent>`
    - :ref:`golden      <optimize.minimize_scalar-golden>`
    - :ref:`bounded     <optimize.minimize_scalar-bounded>`

    `scipy.optimize.root_scalar`

    - :ref:`bisect  <optimize.root_scalar-bisect>`
    - :ref:`brentq  <optimize.root_scalar-brentq>`
    - :ref:`brenth  <optimize.root_scalar-brenth>`
    - :ref:`ridder  <optimize.root_scalar-ridder>`
    - :ref:`toms748 <optimize.root_scalar-toms748>`
    - :ref:`newton  <optimize.root_scalar-newton>`
    - :ref:`secant  <optimize.root_scalar-secant>`
    - :ref:`halley  <optimize.root_scalar-halley>`

    `scipy.optimize.linprog`

    - :ref:`simplex           <optimize.linprog-simplex>`
    - :ref:`interior-point    <optimize.linprog-interior-point>`
    - :ref:`revised simplex   <optimize.linprog-revised_simplex>`
    - :ref:`highs             <optimize.linprog-highs>`
    - :ref:`highs-ds          <optimize.linprog-highs-ds>`
    - :ref:`highs-ipm         <optimize.linprog-highs-ipm>`

    `scipy.optimize.quadratic_assignment`

    - :ref:`faq             <optimize.qap-faq>`
    - :ref:`2opt            <optimize.qap-2opt>`

    Examples
    --------
    We can print documentations of a solver in stdout:

    >>> from scipy.optimize import show_options
    >>> show_options(solver="minimize")
    ...

    Specifying a method is possible:

    >>> show_options(solver="minimize", method="Nelder-Mead")
    ...

    We can also get the documentations as a string:

    >>> show_options(solver="minimize", method="Nelder-Mead", disp=False)
    Minimization of scalar function of one or more variables using the ...

    r   N))bfgsz'scipy.optimize._optimize._minimize_bfgs)cgz%scipy.optimize._optimize._minimize_cg)rV   z*scipy.optimize._cobyla_py._minimize_cobyla)rW   z*scipy.optimize._cobyqa_py._minimize_cobyqa)doglegz3scipy.optimize._trustregion_dogleg._minimize_dogleg)zl-bfgs-bz*scipy.optimize._lbfgsb_py._minimize_lbfgsb)znelder-meadz-scipy.optimize._optimize._minimize_neldermead)z	newton-cgz+scipy.optimize._optimize._minimize_newtoncg)powellz)scipy.optimize._optimize._minimize_powell)rU   z(scipy.optimize._slsqp_py._minimize_slsqp)rT   z!scipy.optimize._tnc._minimize_tnc)z	trust-ncgz3scipy.optimize._trustregion_ncg._minimize_trust_ncg)r^   z?scipy.optimize._trustregion_constr._minimize_trustregion_constr)ztrust-exactz=scipy.optimize._trustregion_exact._minimize_trustregion_exact)ztrust-krylovz9scipy.optimize._trustregion_krylov._minimize_trust_krylov)
)hybrz%scipy.optimize._minpack_py._root_hybr)lmz"scipy.optimize._root._root_leastsq)broyden1z'scipy.optimize._root._root_broyden1_doc)broyden2z'scipy.optimize._root._root_broyden2_doc)andersonz'scipy.optimize._root._root_anderson_doc)diagbroydenz*scipy.optimize._root._root_diagbroyden_doc)excitingmixingz-scipy.optimize._root._root_excitingmixing_doc)linearmixingz+scipy.optimize._root._root_linearmixing_doc)krylovz%scipy.optimize._root._root_krylov_doc)zdf-sanez&scipy.optimize._spectral._root_df_sane))bisectz3scipy.optimize._root_scalar._root_scalar_bisect_doc)brentqz3scipy.optimize._root_scalar._root_scalar_brentq_doc)brenthz3scipy.optimize._root_scalar._root_scalar_brenth_doc)ridderz3scipy.optimize._root_scalar._root_scalar_ridder_doc)toms748z4scipy.optimize._root_scalar._root_scalar_toms748_doc)secantz3scipy.optimize._root_scalar._root_scalar_secant_doc)newtonz3scipy.optimize._root_scalar._root_scalar_newton_doc)halleyz3scipy.optimize._root_scalar._root_scalar_halley_doc))simplexz,scipy.optimize._linprog._linprog_simplex_doc)zinterior-pointz'scipy.optimize._linprog._linprog_ip_doc)zrevised simplexz'scipy.optimize._linprog._linprog_rs_doc)z	highs-ipmz.scipy.optimize._linprog._linprog_highs_ipm_doc)zhighs-dsz-scipy.optimize._linprog._linprog_highs_ds_doc)highsz*scipy.optimize._linprog._linprog_highs_doc))faqz-scipy.optimize._qap._quadratic_assignment_faq)2optz.scipy.optimize._qap._quadratic_assignment_2opt))r   z/scipy.optimize._optimize._minimize_scalar_brent)boundedz1scipy.optimize._optimize._minimize_scalar_bounded)r	   z0scipy.optimize._optimize._minimize_scalar_golden)minimizerootroot_scalarlinprogquadratic_assignmentminimize_scalar)z


========
z	minimize
z	========
r  F)r   )z

===============
zminimize_scalar
z===============
r  )z


====
zroot
z====
r  )z


=======
zlinprog
z=======
r  r  zUnknown solver z

rc  =zUnknown method .r   )textwrapr  r   extendr|   lowerru   r  rp  split
__import__getattrsysmodulesrQ   dedentstripr  )r2  rj   r   r  doc_routinestextnamer^  methodspartsmod_nameobjdocs                r?   r   r   F  s   V OOO
,
	

!

s> >L@ ~???L%888999 * * * 	+ 	+ 	+L!2???@@@    	  	  	 Le444555 " " " 	# 	# 	#L777888wwt}}%%9v99:::>D'/ D DaVd]D3s4yy=,@6,IJKKKLEBBBCCCC774==DD\\^^F</00GW$$ !=6!=!=>>>6?D JJsOOExxcrc
++Hx   #+h/r;;C +Cs++1133 drA   r9   )r   )NrR   NNNN)
rR   r   r   NNr   r!   r   NN)rR   NNNFFNr   r   FN)rR   rm  r  r   r!   )rR   rm  r  r   )rR   Nr  r   r  )NrR   r  r  r   )r{  r   rR   r!  r"  )rC  NNN)
rR   NNr   r   NNFNF)NNT)e__all____docformat__r  r   r  re   numpyr   r   r   r   r   r   rC   scipy.linalgr   r   r   scipy.sparse.linalgr    _linesearchr"   r#   r   r$   _numdiffr%   scipy._lib._utilr&   ro  r'   r(   r)   r*   r+   (scipy.optimize._differentiable_functionsr,   r-   scipy._lib._array_apir.   
scipy._libr/   r   r  r7   rl   r   UserWarningr   rw   r   r   r  r  rq  _epsilonr   r   r   r   r   r   r   r   r   r$  r   r   r   r   r   r   rW  rY  rl  r   r   rv  r  r   r  r   r  r   r  r  r   r  r	   r  r
   r%  r6  rB  rO  r   rV  r  r   rn  r   rR   rA   r?   <module>r     s6  (   &   



  : : : : : : : : : : : : : : : :     ; ; ; ; ; ; ; ; ; ; . . . . . .- - - - - - - - - - - - ( ' ' ' ' ' F F F F F FM M M M M M M M M M M M M M O O O O O O O O 1 1 1 1 1 1 - - - - - - F/*33%.	/ 	/       6   0*	 *	 *	 *	 *	[ *	 *	 *	Z	 	 	 	 	k 	 	 	L L LW W W. . . 4#$$; ; ; ; AE@D"&[ [ [ [|
 
 
  0 0 0f' ' 'T(4 (4 (4V* * *Z$ $ $0	 	 	 	 	 	 	 	$ $ $6 HLIMz z z zz 6:9>;?HLL L L L^ "* N/ N/ N/ N/b F+++.6TZ Z Z Z ,+Zz  	 	 	 	 	| 	 	 	* * *Z !r26!!Q4CM M M M` "$26x%dt!	n n n nbJ J J J Rdd!dst t t tn  "tdXtDSW W W Wt %)2tt1tu u u up &(TD $4Xt!ey! y! y! y!x 8;"#[ [ [ [| 13;<S S S Slr r r r r r r rjM M M M` <C-.6< 6< 6< 6<r ($J J J JZ )-2!)4au< u< u< u<p\, \, \, \,~	 	 	 	 	< 	 	 	  D<4 <4 <4~ )-@D6' 6' 6' 6'r BFGKK K K K\ ?C@D8=o o o od  $  BAdaB B B BJ; ; ; ; ; ; ; ;] ] ] ] ] ]rA   