
    (ph@                       / S Qr SrSSKrSSKrSSKrSSKrSSKJrJrJ	r	J
r
JrJr  SSKrSSKJrJrJr  SSKJr  SSKJrJrJrJr  SS	KJr  SS
KJr  SSKJrJrJ r J!r!J"r"  SSK#J$r$J%r%  SSK&J'r'  SSK(J)r*  SSSSSSS.r+ " S S5      r,S]S jr- " S S\ 5      r. " S S\/5      r0S r1S r2S r3\" \Rh                  " \55      Rl                  5      r7S^S  jr8   S_S" jr9S# r:S$ r;S% r<S& r=S' r>S( r?S) r@ " S* S+\A5      rBS, rC  S`S. jrD    SaS0 jrE\74S1 jrF\"" S2S3S49\7S5SS6.S7 j5       rGS8 rH " S9 S:\A5      rIS; rJSS!S<\R                  \7SSSSSSS-S=S4S> jrLS!SSS<\R                  \7SS/S/SSS-S=S4S? jrMS]S@ jrNSS!S<\R                  \7SSSSSS-SA4SB jrOS!SSS<\R                  \7SS/S/SS-SA4SC jrPSSS!S<\7SSSSSS-S=4SD jrQS!SSSSS<\7SS/S/S-S=4SE jrR  SbSF jrS  ScSG jrT " SH SI5      rUSdSJ jrV  SeSK jrWS!S\7SSL4SM jrXSS!\7SLS4SN jrYSfSO jrZ " SP SQ\A5      r[SR r\SS r]  SgST jr^   S`SU jr_   ShSV jr`SW raS!SXS\DS/S4SY jrb " SZ S[5      rcSiS\ jrdg)j)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                   0    \ rS rSrSrS rS rS rS rSr	g)	
MemoizeJac=   zgDecorator that caches the return values of a function returning ``(fun, grad)``
each time it is called.c                 :    Xl         S U l        S U l        S U l        g N)funjac_valuex)selfr;   s     K/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_optimize.py__init__MemoizeJac.__init__A   s        c                 (   [         R                  " XR                  :H  5      (       a  U R                  b  U R                  cQ  [         R
                  " U5      R                  5       U l        U R                  " U/UQ76 nUS   U l        US   U l        g g )Nr!   r   )npallr>   r=   r<   r   copyr;   )r?   r>   argsfgs       r@   _compute_if_neededMemoizeJac._compute_if_neededG   sp    vva66k""dkk&9TXX=MZZ]'')DF!#d#B!uDHQ%DK	 >NrC   c                 @    U R                   " U/UQ76   U R                  $ )zreturns the function value )rJ   r=   r?   r>   rH   s      r@   __call__MemoizeJac.__call__N   s    )D){{rC   c                 @    U R                   " U/UQ76   U R                  $ r:   )rJ   r<   rM   s      r@   
derivativeMemoizeJac.derivativeS   s    )D)xxrC   )r=   r;   r<   r>   N)
__name__
__module____qualname____firstlineno____doc__rA   rJ   rN   rQ   __static_attributes__ rC   r@   r7   r7   =   s     
rC   r7   c                    ^  T b  US;   a  T $ [         R                  " T 5      n[        UR                  5      S1:X  a  U 4S jnO US:X  a  U 4S jnOUS:X  a  U 4S jnOU 4S jnS	Ul        U$ )
zAWrap a user-provided callback so that attributes can be attached.>   tncslsqpcobylacobyqaintermediate_resultc                    > T" U S9$ )N)r_   rY   rescallbacks    r@   wrapped_callback(_wrap_callback.<locals>.wrapped_callback`   s    44rC   trust-constrc                 R   > T" [         R                  " U R                  5      U 5      $ r:   rE   rG   r>   ra   s    r@   rd   re   c   s    BGGCEENC00rC   differential_evolutionc                 f   > T" [         R                  " U R                  5      U R                  5      $ r:   )rE   rG   r>   convergencera   s    r@   rd   re   f   s     BGGCEENCOO<<rC   c                 P   > T" [         R                  " U R                  5      5      $ r:   rh   ra   s    r@   rd   re   i   s    BGGCEEN++rC   F)inspect	signatureset
parametersstop_iteration)rc   methodsigrd   s   `   r@   _wrap_callbackrt   X   sq    6%II


H
%C
3>>455	5	>	!	1	+	+	=	, ',#rC   c                       \ rS rSrSrSrg)r   p   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.

rY   N)rS   rT   rU   rV   rW   rX   rY   rC   r@   r   r   p   s    (R 	rC   r   c                       \ rS rSrSrg)r      rY   NrS   rT   rU   rV   rX   rY   rC   r@   r   r          rC   r   c                 B    S nU b  U" U 5      (       d  [        S5      eg g )Nc                 ^    [        U 5      (       a   [        U 5        gg! [         a     gf = f)NTF)r   r   r   )As    r@   
is_pos_def,_check_positive_definite.<locals>.is_pos_def   s3    q>>   s    
,,z+'hess_inv0' matrix isn't positive definite.)
ValueError)Hkr~   s     r@   _check_positive_definiter      s-     
~"~~JKK  rC   c                     U (       aK  SR                  [        [        U R                  5       5      5      n[        R
                  " SU 3[        SS9  g g )Nz, zUnknown solver options:    
stacklevel)joinmapstrkeyswarningswarnr   )unknown_optionsmsgs     r@   _check_unknown_optionsr      sC    iiC!5!5!789 	06TUV rC   c                 n    [         R                  " U 5      S:H  =(       a    [         R                  " U 5      $ )zJTest whether `x` is either a finite scalar or a finite array scalar.

    r!   )rE   sizeisfinite)r>   s    r@   is_finite_scalarr      s#     771:?-r{{1~-rC   c                 `   U[         R                  :X  a*  [         R                  " [         R                  " U 5      5      $ U[         R                  * :X  a*  [         R                  " [         R                  " U 5      5      $ [         R
                  " [         R                  " U 5      U-  SS9SU-  -  $ )Nr   axis      ?)rE   infamaxabsaminsum)r>   ords     r@   vecnormr      sn    
bff}wwrvvay!!	wwrvvay!!vvbffQin1-c	::rC   rY   c                     [        U5      (       a  UnOU[        ;   a  SnUnOSnUnUc  S nUc!  [        R                  * [        R                  4n[	        XX8UXdUS9n	U	$ )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                     g r:   rY   )r>   rH   s     r@   hess&_prepare_scalar_function.<locals>.hess  s    rC   )epsilon)callabler-   rE   r   r,   )
r;   x0r<   rH   boundsr   finite_diff_rel_stepr   gradsfs
             r@   _prepare_scalar_functionr      sw    x }}	
	  |
	 ~66'266" 
T,g
GB IrC   c                    ^ ^ UU 4S jnU$ )Nc                 ,   > [        U T5      n T" U 5      $ r:   )_check_clip_x)r>   r   funcs    r@   eval_clip_x_for_func.<locals>.eval/  s    !V$AwrC   rY   )r   r   r   s   `` r@   _clip_x_for_funcr   )  s     KrC   c                     XS   :  R                  5       (       d  XS   :  R                  5       (       a9  [        R                  " S[        SS9  [        R
                  " XS   US   5      n U $ U $ )Nr   r!   zJValues in x were outside bounds during a minimize step, clipping to bounds   r   )anyr   r   RuntimeWarningrE   clip)r>   r   s     r@   r   r   6  se    	1IAY 3 3 5 5 :$	4 GGAay&),HrC   c                 F   [        U 5      nUR                  U 5      n UR                  U R                  S5      (       a*  UR	                  XR                  S5      R                  5      n UR                  SU SS U SS S-  -
  S-  -  SU SS -
  S-  -   SU R                  S	9nU$ )
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3BZ#4EEQWW 	 	&AHrC   c                    [        U 5      nUR                  U 5      n UR                  U R                  S5      (       a*  UR	                  XR                  S5      R                  5      n U SS nU SS nU SS nUR                  U 5      nSX#S-  -
  -  S	XBS-  -
  -  U-  -
  SSU-
  -  -
  USS& S
U S   -  U S   U S   S-  -
  -  SSU S   -
  -  -
  US'   SU S   U S   S-  -
  -  US'   U$ )a   
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   N        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--.	
1RBcrFEabEE
--
CAX&A&+,./1r6l;C"IAaD[AaD1Q47N+a1qt8n<CFQrUQrUAX%&CGJrC   c                 :   [        U 5      n[        R                  " U SUS9n UR                  U R                  S5      (       a*  UR                  XR                  S5      R                  5      n [        R                  " SU SS -  SUS9[        R                  " S	U SS -  SUS9-
  nUR                  U R                  S
   U R                  S9nSU S
   S-  -  S	U S   -  -
  S-   US
'   SUS'   SSU SS S-  -  -   S	U SS -  -
  USS& U[        R                  " X1S9-   $ )a9  
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     s"   < 
	BqqR(A	zz!'':&&IIaB--.			TAcrF]1	<sQsV|B2>
?Axx
!''x2H1q.31:-1HQKHRL4!Ab'1*,,sQqrU{:HQrNs""8333rC   c                 l   [        X5      n[        R                  " U SUS9n UR                  U R                  S5      (       a*  UR                  XR                  S5      R                  5      n UR                  XR                  S9nUR                  U R                  S   U R                  S9nSU S   S-  -  S	U S   -  -
  S-   US   -  S	U S   -  US   -  -
  US'   S
U SS -  USS -  SSU SS S-  -  -   S	U SS -  -
  USS -  -   S	U SS -  USS -  -
  USS& S
U S   -  US   -  SUS   -  -   US'   U$ )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     sk   > 
	BqqR(A	zz!'':&&IIaB--.


1GG
$A	!''!*AGG	,BAaD!G^cAaDj(1,!4sQqTzAaD7HHBqEq"v#2&ta"gqj((312;6!Ab'ABa"g!"%&BqH AbE\AbE!C"I-BrFIrC   c                 4   ^ ^^ S/mT c  TS 4$ UU U4S jnTU4$ )Nr   c                 .  > TS==   S-  ss'   T" [         R                  " U 5      /UT-   Q76 n[         R                  " U5      (       d'   [         R                  " U5      R	                  5       nU$ U$ ! [
        [        4 a  n[        S5      UeS nAff = f)Nr   r!   @The user-provided objective function must return a scalar value.)rE   rG   isscalarr   item	TypeErrorr   )r>   wrapper_argsfxerH   functionncallss       r@   function_wrapper/_wrap_scalar_function.<locals>.function_wrapper  s    q	Q	bggaj9L4$79 {{2GZZ^((* 	r	 z* G  "? @EFGGs   $A3 3BBBrY   )r   rH   r   r   s   `` @r@   _wrap_scalar_functionr     s/     SFt| ###rC   c                       \ rS rSrSrg)_MaxFuncCallErrori  rY   Nry   rY   rC   r@   r   r     rz   rC   r   c                 8   ^ ^^^ S/mT c  TS 4$ UU UU4S jnTU4$ )Nr   c                 V  > TS   T:  a  [        S5      eTS==   S-  ss'   T" [        R                  " U 5      /UT-   Q76 n[        R                  " U5      (       d'   [        R                  " U5      R                  5       nU$ U$ ! [        [        4 a  n[        S5      UeS nAff = f)Nr   zToo many function callsr!   r   )r   rE   rG   r   r   r   r   r   )r>   r   r   r   rH   r   maxfunr   s       r@   r   A_wrap_scalar_function_maxfun_validation.<locals>.function_wrapper  s    !9#$=>>q	Q	bggaj9L4$79 {{2GZZ^((* 	r	 z* G  "? @EFGGs   $B B(B##B(rY   )r   rH   r   r   r   s   ``` @r@   '_wrap_scalar_function_maxfun_validationr     s4     SFt| " ###rC   -C6?c                     UUUUUU	US.n[        U
5      n
[        XU4SU
0UD6nU(       a'  US   US   US   US   US   4nU	(       a  XS   4-  nU$ U	(       a
  US   US   4$ U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_simplexrc   r>   r;   nitnfevstatusallvecs)rt   _minimize_neldermead)r   r   rH   xtolftolr2   r   full_outputr   retallrc   r   optsrb   retlists                  r@   r   r   -  s    N  .0D h'H
t
I
ID
ICc(CJE
CKXNI))Gs8S^++s8OrC   Fc                 j   [        U5        UnUn[        R                  " U5      R                  5       n[        R                  " UR
                  [        R                  5      (       a  UR
                  O[        R                  n[        R                  " UUS9nU(       a2  [        [        U5      5      nSnSSU-  -   nSSSU-  -  -
  nSSU-  -
  nOSnSnSnSnSnSnUb  UR                  UR                  nnUU:  R                  5       (       a  [        S	5      e[        R                  " UU:  5      (       d  [        R                  " UU:  5      (       a  [        R                   " S
["        SS9  Ub  [        R$                  " UWW5      nUc  [        U5      n[        R&                  " US-   U4UR
                  S9nUUS'   [)        U5       H=  n[        R*                  " USS9nUU   S:w  a  SU-   UU   -  UU'   OUUU'   UUUS-   '   M?     O[        R,                  " U5      R/                  5       n[        R                  " UR
                  [        R                  5      (       a  UR
                  O[        R                  n[        R                  " UUS9nUR0                  S:w  d#  UR2                  S   UR2                  S   S-   :w  a  [        S5      e[        U5      UR2                  S   :w  a  [        S5      eUR2                  S   nU(       a  US   /nUc  Uc  US-  nUS-  nO[Uc+  U[        R4                  :X  a  US-  nO>[        R4                  nO-Uc*  U[        R4                  :X  a  US-  nO[        R4                  nUb;  UW:  n[        R6                  " USU-  U-
  U5      n[        R$                  " UWU5      n[9        [)        SUS-   5      5      n [        R:                  " US-   4[        R4                  [        S9n![=        XU5      u  n"n  [)        US-   5       H  nU " UU   5      U!U'   M     [        R@                  " U!5      n#[        RB                  " UU#S5      n[        RB                  " U!U#S5      n![        R@                  " U!5      n#[        RB                  " U!U#S5      n![        RB                  " UU#S5      nSn$U"S   U:  Gas  U$U:  Gal   [        RD                  " [        RF                  " [        RH                  " USS US   -
  5      5      5      U	::  a  [        RD                  " [        RH                  " U!S   U!SS -
  5      5      U
::  a   [        R@                  " U!5      n#[        RB                  " UU#S5      n[        RB                  " U!U#S5      n!U(       a  WRK                  US   5        [M        US   U!S   S9n%[O        UU%5      (       Gae  GOc[        RP                  RS                  USS S5      U-  n&SU-   U&-  UUS   -  -
  n'Ub  [        R$                  " U'WW5      n'U " U'5      n(Sn)U(U!S   :  aX  SUU-  -   U&-  UU-  US   -  -
  n*Ub  [        R$                  " U*WW5      n*U " U*5      n+U+U(:  a  U*US'   U+U!S'   GOU'US'   U(U!S'   GOU(U!S   :  a  U'US'   U(U!S'   OU(U!S   :  aN  SUU-  -   U&-  UU-  US   -  -
  n,Ub  [        R$                  " U,WW5      n,U " U,5      n-U-U(::  a  U,US'   U-U!S'   OMSn)OJSU-
  U&-  UUS   -  -   n.Ub  [        R$                  " U.WW5      n.U " U.5      n/U/U!S   :  a  U.US'   U/U!S'   OSn)U)(       aO  U  HI  n0US   UUU0   US   -
  -  -   UU0'   Ub  [        R$                  " UU0   WW5      UU0'   U " UU0   5      U!U0'   MK     U$S-  n$[        R@                  " U!5      n#[        RB                  " UU#S5      n[        RB                  " U!U#S5      n!U(       a  WRK                  US   5        [M        US   U!S   S9n%[O        UU%5      (       a  O U"S   U:  a	  U$U:  a  GMl  US   n1[        RT                  " U!5      n2Sn3U"S   U:  a-  Sn3[V        S   n4U(       a  [        R                   " U4[X        SS9  O|U$U:  a-  Sn3[V        S   n4U(       a  [        R                   " U4[X        SS9  OI[V        S   n4U(       a9  [[        U45        [[        SU2S 35        [[        SU$-  5        [[        SU"S   -  5        [M        U2U$U"S   U3U3S:H  U4U1UU!4S9n5U(       a  WU5S'   U5$ ! [>         a     GNf = f! [        R@                  " U!5      n#[        RB                  " UU#S5      n[        RB                  " U!U#S5      n!f = f! [>         a     GNf = f! [        R@                  " U!5      n#[        RB                  " UU#S5      n[        RB                  " U!U#S5      n!U(       a  WRK                  US   5        [M        US   U!S   S9n%[O        UU%5      (       a     GM  f = f)a  
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   r   r   T)rG   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   rE   
atleast_1dflatten
issubdtyper   inexactfloat64r   floatlenlbubr   r   r   r   r   r   emptyrangearray
atleast_2drG   r   r   r   wherelistfullr   r   argsorttakemaxravelr   appendr   r*   addreducemin_status_messager   print)6r   r   rH   rc   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
iterationsr_   xbarxrfxrdoshrinkxefxexcfxcxccfxccjr>   fvalwarnflagr   results6                                                         r@   r   r     s	   l ?+FF	r		"	"	$Bbhh

;;BHHE	Be	$BCGn!C%iQ#YAcE	HE#)99fii[+%**,, ? @ @66+"##rvvb;.>'?'?MML)a9 WWRk2GhhAqz2AqA$'AtqyHad*!!CAJ  mmO,113]]399bjjAA		rzzjjE*88q=CIIaLCIIaL1,<<TUUr7ciil"TUUIIaLq6( 6>c'S	 RVV#gGffG	bffWFVVF KhhsAkMC/5ggc;45AE?#G77AE8RVV51D:4vNLFD%q1uA3q6lDG 
 jjggc3"wwtS!$
**T
C774a D
''#sA
CJ!9v*w"6H	rxxs12wQ'7 89:eCFF266$q'DH"456%?| **T"C''#sA&C774a(Ds1v&"03q6tAw"G(3FGGG 66==Sb1-1Dc'T!C#b'M1B!WWRk:r(CHT!W}#)mt+cCi#b'.AA%[+>B2h9 CG"DH CG"DHb> CG"DH T"X~#)mt3cCi#b'6II!-!#[+!FB"2h#:&(CG'*DH'(H  !3w$.s2w>!-"$''#{K"HC#Cy$r(?&)CG'+DH'(H!(A%(Ves1vA.G%GCF%1)+$'FK*FA&*3q6lDG ") !OJ **T"C''#sA&C774a(Ds1v&"03q6tAw"G(3FGG HQ !9v*w"6V 	AA66$<DHayFh'MM#~!<	w	i(MM#~!<i(#J5d1X>?+j895q	AB*6!9#+h!m$'1S$KIF #yMi   jjggc3"wwtS!$P ! 		 **T"C''#sA&C774a(Ds1v&"03q6tAw"G(3FGG HsX   #d< Bf $Gf <
e
e 	e

e Af
f&"f) %f&&f) )Bh21h2c           	      b    [         R                  " U [        5      n U" U /UQ76 n[        XSUX4S9$ )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   )rr   abs_steprH   f0)rE   r   r  r%   )xkr  r   rH   rJ  s        r@   r   r     s8    T 
B	B	
2BQ9w"&/ /rC   seed   )position_numrF   )r   	directionrngc                N   Un[         R                  " U5      nS nUS:X  a  [         R                  " U" U/UQ76 5      n	U	R                  S:  a  [	        S5      e[        U5      n
U
R                  UR                  S9nXU4U-   nUn[         R                  " S5      n[         R                  " X5      nO$US:X  a  UnU nUnU" U/UQ76 nO[	        U S35      e[         R                  " [         R                  " [         R                  " U[        XU/UQ76 -
  S	-  5      5      5      $ )
a  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                     U" X U-  -   /UQ76 $ r:   rY   )wr   r   vrH   s        r@   gcheck_grad.<locals>.gL  s    B1H$t$$rC   randomr!   z1'random' can only be used with scalar valued func)r   r!   rF   z1 is not a valid string for ``direction`` argumentr   )rE   r   
asanyarrayr   r   r(   standard_normalr   r   dotr   r   r   r   )r   r   r   r   rO  rP  rH   steprU  _gradrng_genrT  _args_funcvarsanalytical_grads                   r@   r   r   
  s)   ~ D	BB% Hd2oo.::> % & &$S)##"((#41$xx~&&*	e	r/D/I; '2 2 3 	3 77266"&&	=dCUC	CaG   rC   c                 >    U" U 4U-   6 nU" XU-  -   4U-   6 nXe-
  U-  $ r:   rY   )r   r   fprimer   rH   f1f2s          r@   approx_fhess_prg  h  s7    	2%$,	 B	2	>#d*	,BGwrC   c                       \ rS rSrSrg)_LineSearchErrorio  rY   Nry   rY   rC   r@   ri  ri  o  rz   rC   ri  c           
         UR                  SS5      n[        XX#UXV40 UD6n	U	S   b'  Ub$  X)S   U-  -   n
U" U	S   XS   U	S   5      (       d  Sn	U	S   cb  [        R                  " 5          [        R                  " S[
        5        0 nS H  nX;   d  M
  X|   X'   M     [        XX#UXV4SU0UD6n	SSS5        U	S   c
  [        5       eU	$ ! , (       d  f       N = f)	z
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      r:   ignore)c1c2r   )popr"   r   catch_warningssimplefilterr$   r#   ri  )r  rd  rK  pkgfkold_fvalold_old_fvalkwargsrk  retxp1kwargs2keys                r@   _line_search_wolfe12r|  s  s    jj!2D9O
Q%'%'C 1vo9q6B;s1vsFCF;;C
1v~$$&!!(,=>G+=#);GL , %Q%-05D0 (/0C ' 1v~  J '&s   *&C	C		
Ch㈵>g?c                     UUUU	UU
UUUUS.
n[        U5      n[        XX24SU0UD6nU(       a0  US   US   US   US   US   US   US	   4nU
(       a	  UUS
   4-  nU$ U
(       a
  US   US
   4$ U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   xrtolrn  ro  	hess_inv0rc   r>   r;   r<   hess_invr   njevr   r   )rt   _minimize_bfgs)r  r   rd  rH   r  r  r   r2   r   r   r   rc   r  rn  ro  r  r   rb   r  s                      r@   r   r     s    j  "	$D h'H

Hx
H4
HCs8SZUS_v;FS]<I))Gs8S^++s8OrC   c                 p   [        U5        [        U5        U
n[        U5      R                  5       nUR                  S:X  a  SUl        Uc  [        U5      S-  n[        XX2UUS9nUR                  nUR                  nU" U5      nU" U5      nSn[        U5      n[        R                  " U[        S9nUc  UOUnU[        R                  R                  U5      S-  -   nUnU(       a  U/nSn[        UUS9nUU:  Ga  UU:  Ga  [        R                   " UU5      * n  [#        UUUU UUUS	S
XS9u  n!n"n#nnn$U!U -  n%UU%-   n&U(       a  WR'                  U&5        U&nU$c  U" U&5      n$U$U-
  n'U$nUS-  n[)        UUS9n([+        UU(5      (       a  GOe[        UUS9nUU::  a  GOSU![        U 5      -  X[        U5      -   -  ::  a  GO1[        R,                  " U5      (       d  SnGO[        R                   " U'U%5      n)U)S:X  a  Sn*U	(       a  Sn+[/        SU+5        OSU)-  n*UU%SS2[        R0                  4   U'[        R0                  SS24   -  U*-  -
  n,UU'SS2[        R0                  4   U%[        R0                  SS24   -  U*-  -
  n-[        R                   " U,[        R                   " UU-5      5      U*U%SS2[        R0                  4   -  U%[        R0                  SS24   -  -   nUU:  a	  UU:  a  GM  Un.US:X  a
  [2        S   n+OUU:  a  Sn[2        S   n+Ot[        R4                  " U5      (       dD  [        R4                  " U.5      (       d)  [        R4                  " U5      R7                  5       (       a  Sn[2        S   n+O	[2        S   n+U	(       aY  [/        UU+5        [9        SU.S 35        [9        SU-  5        [9        SUR:                  -  5        [9        SUR<                  -  5        [)        U.UUUR:                  UR<                  UUS:H  U+UUS9
n/U(       a  WU/S'   U/$ ! [$         a    Sn GM?  f = f)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   rX  Nr   )rH   r   r   r   r   r   0.++}Ô%IT)r   r   rn  ro  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<   r  r   r  r   r0   r
  r>   r   r   )r   r   r   r  r   r   r  r   r;   r   rE   r   intlinalgr  r   r[  r|  ri  r   r   r*   r   _print_success_message_or_warnnewaxisr$  isnanr   r%  r   ngev)0r;   r   rH   r<   rc   r  r  r  r2   r   r   r   r  rn  ro  r  r   r   r   r  myfprimeru  rt  r2  r0  Ir   rv  rK  r   rF  gnormrs  alpha_kfcgcgfkp1skxkp1ykr_   rhok_invrhokr   A1A2rE  rG  s0                                                   r@   r  r  0  s   n ?+Y'F				B	ww!|b'C-	!#337K
MB 	AwwHuH
2,C	ABA
qAYB biinnS1A55L	B$HCT"E4<a'kffRo	)!Xr2s*2Lv/4D ;GRX|U r\BwNN4 =TNES[	Q,rx@$X/BCC&TM GBK5'"+*=#>>{{8$$ H66"b> r>DF.tS9=DArzzM"R

A%66==ArzzM"R

A%66==VVBr2'4"Q

]2C+C13BJJM1B,C Du 4<a'kz D1}i(	
gi(	%BHHTNNbhhrl.>.>.@.@e$i(&x51$q:;'!+,1BGG;<1BGG;<#!#%-]SB !#F #yMa   	H	s   P$ $P54P5c                 n    U (       d  [        U5        g [        R                  " X=(       d    [        SS9  g )Nr   r   )r%  r   r   r   )rF  r
  warntypes      r@   r  r    s    gg:?qIrC   g?c                     UUUU	UU
S.n[        U5      n[        XX24XUS.UD6nU(       a(  US   US   US   US   US   4nU
(       a	  UUS   4-  nU$ U
(       a
  US   US   4$ U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])

)r  r  r  r   r2   r   rc   rn  ro  r>   r;   r   r  r   r   )rt   _minimize_cg)r  r   rd  rH   r  r  r   r2   r   r   r   rc   rn  ro  r   rb   r  s                    r@   r   r     s    @  "D h'H
qd X C c(CJFS[#h-OI))Gs8S^++s8OrC   c                 v  ^^^!^"^#^$^%^&^'^( [        U5        U
n[        U5      R                  5       nUc  [        U5      S-  n[	        XX2UUS9nUR
                  nUR                  m$U" U5      nT$" U5      m#SnUm(U[        R                  R                  T#5      S-  -   nU(       a  T(/nSnT#* m%[        T#TS9nSm'UT:  a  UU:  a  [        R                  " T#T#5      m"S/m!SU"U#U$UU%U(4S jjm&U!UU&U'4S	 jn [        UT$T(T%T#UUXS
SUS9u  nnnnnnUT!S   :X  a	  T!u  nm(m%m#nOT&" UU5      u  nm(m%m#nU(       a  WR                  T(5        US-  n[        T(US9n[!        UU5      (       a  OUT:  a  UU:  a  M  UnUS:X  a
  ["        S   nOUU:  a  Sn["        S   nOt[        R$                  " U5      (       dD  [        R$                  " U5      (       d)  [        R$                  " T(5      R'                  5       (       a  Sn["        S   nO	["        S   nU	(       aY  [)        UU5        [+        SUS 35        [+        SU-  5        [+        SUR,                  -  5        [+        SUR.                  -  5        [        UT#UR,                  UR.                  UUS:H  UT(US9	n U(       a  WU S'   U $ ! [         a    Sn GM>  f = f)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<   rH   r   r   r   r   r  g{Gz?c                    > TU T-  -   nUc  T	" U5      nUT-
  n[        S[        R                  " X15      T-  5      nU* UT-  -   n[        UT
S9nXXQU4$ )Nr   r  )r  rE   r[  r   )alphar  r  r  beta_kpkp1r  deltakrt  r  r  rs  rK  s          r@   polak_ribiere_powell_step/_minimize_cg.<locals>.polak_ribiere_powell_step  sj    
?D} BBFF2-67F6FRK'DEt,Ee44rC   c                    > T
" X5      TS S & Tu  ppVnUT	::  a  g[         R                  " XV5      T* [         R                  " Xf5      -  :*  $ )NT)rE   r[  )r  r  fp1r  rK  rs  rt  r  cached_stepr  r  sigma_3s           r@   descent_condition'_minimize_cg.<locals>.descent_condition  sP     7uDKN(3%Er } 66"?wh1A&AAArC   r  r  )rn  ro  r   r   rk  r!   r  r3   r2   r   r4   r0   r  r  r  r	  r  )	r;   r<   r   r  r   r0   r
  r>   r   r   r:   )r   r   r  r  r   r;   r   rE   r  r  r   r[  r|  ri  r   r   r*   r$  r  r   r  r%  r   r  ))r;   r   rH   r<   rc   r  r  r  r2   r   r   r   rn  ro  r   r   r   r  ru  r2  rv  r   rF  r  r  r  r  r  r  r_   rE  r   rG  r  r  rt  r  rs  r  r  rK  s)        ``                          @@@@@@@@r@   r  r    s   R ?+F				Bb'C-	!#ss7K
MB 	AwwHuH
2,C	A	BbiinnS1A55L$H
BCT"EG4<a'kS!f	5 	5	B 	B"	)!Xr2sH*626/4FWY ;GRX|U k!n$*5'GRS%*CGU*S'GRS%NN2	Q,rx@$X/BCCk 4<a'kn D1}i(	
gi(	%BHHTNNbhhrl.>.>.@.@e$i(&x51$q:;'!+,1BGG;<1BGG;<#BGG!#%-]SB !#F #yMW   	H	s   7J' 'J87J8c                     UUUU
US.n[        U5      n[        XXRXC4XUS.UD6nU	(       a,  US   US   US   US   US   US   4nU(       a	  UUS	   4-  nU$ U(       a
  US   US	   4$ U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   r  r2   r   r   r  r>   r;   r   r  nhevr   r   )rt   _minimize_newtoncg)r  r   rd  fhess_pfhessrH   avextolr   r2   r   r   r   rc   rn  ro  r   rb   r  s                     r@   r   r   9  s    B  	"D h'H
QD% F&."F@DFC s8SZVc&kv;H/I))Gs8S^++s8OrC   c                   ^
^4^5^6^7^8^9^:^; [        U5        Uc  [        S5      eUnUnUnUnUm9[        U5      R                  5       n[	        XX2XS9m:T:R
                  nT:R                  nT:R                  U5      nU[        ;   d  [        U[        5      (       a
  SnU:4S jnUnU4U
U5U6U7U8U9U:U;4	S jnSm6U	c  [        U5      S-  n	S[        U5      -  n[        U5      U-  n[        R                  " [        5      R                  n[        R                   " U5      m;T9(       a  T;/m4Sm7Sm5U" U5      m8Sn[        R                  " [        R"                  5      R$                  nUU:  Gax  T7U	:  a  S	[&        S
   -   nU" SU5      $ U" T;5      * n[        R(                  R+                  USS9n[-        S[.        R0                  " U5      5      nUU-  n [3        [        U5      UR4                  S9n!U* n"U"* n#Sn$[        R6                  " U"U"5      n%Ub  T:R                  T;5      n&T6S-  m6[9        U5       GH  n'[        R:                  R=                  [        R>                  " U"5      5      U ::  a    OUc"  Uc  [A        T;U#UU5      n(O!U" T;U#/UQ76 n(T6S-  m6OW&R7                  U#5      n([        U(5      RC                  5       n([        R6                  " U#U(5      n)SU)s=::  a	  SU-  ::  a  O  O  OjU)S:  a  U$S:  a    O\U%U)* -  U-  n!  OQU%U)-  n*U!U*U#-  -  n!U"U*U(-  -  n"[        R6                  " U"U"5      n+U+U%-  n,U"* U,U#-  -   n#U$S-  n$U+n%GM     SnU" SU5      $ U!n-U* m5 [E        UUT;U-T5T8UXS9	u  n.n/n0m8nn1U.U--  n2T;U2-  m;T9(       a  T4RI                  T;5        T7S-  m7[K        T;T8S9n3[M        UU35      (       a	  U" SS5      $ [        R(                  R+                  U2SS9nUU:  a  GMx  [        RN                  " T85      (       d  [        RN                  " U5      (       a  U" S[&        S   5      $ [&        S   nU" SU5      $ ! [F         a    S	[&        S   -   nU" SU5      s $ f = f)a  
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)rH   r   r   c                 D   > TR                  U 5      R                  U5      $ r:   )r   r[  )r>   r   rH   r   s      r@   _hessp"_minimize_newtoncg.<locals>._hessp  s    771:>>!$$rC   c                 P  >	 T(       af  [        X5        [        ST	S 35        [        ST-  5        [        STR                  -  5        [        STR                  -  5        [        ST-  5        T	n[	        UTTR                  TR                  TU U S:H  UTTS9
nT
(       a  TUS	'   U$ )
Nr  r  r  r	  r  z          Hessian evaluations: %dr   )
r;   r<   r   r  r  r   r0   r
  r>   r   r   )r  r%  r   r  r   )rF  r   rE  rG  r   r   rt  hcallsr2  ru  r   r   rK  s       r@   	terminate%_minimize_newtoncg.<locals>.terminate  s    *895hq\BC+a/05?@5?@4v=>Dc%'WW6()1Q$%'  'F9rC   r   r      z	Warning: r2   r!   r  r  r   r   zMWarning: CG iterations didn't converge. The Hessian is not positive definite.)rn  ro  r3   r   r  rl   r4   r0   )(r   r   r   r  r   r;   r   r   r-   
isinstancer    r  rE   finfor  r  rG   r  r  r$  r  r  r#  mathr   r   r   r[  r  r!  r"  r   rg  squeezer|  ri  r   r   r*   r  )<r;   r   rH   r<   r   hessprc   r   r  r2   r   r   rn  ro  r   r  r  r  r   r  rd  _hr  r  
cg_maxiterupdate_l1normrv  
float64epsr   bmaggradetatermcondxsupiripsupiidri0r}   k2Apcurvalphaidri1betairs  alphakr  r  r  updater_   r   rt  r  r2  ru  r   r   rK  s<             `                                         @@@@@@@@r@   r  r    s`   B ?+
{DEEGEGGF				B	!
B 	AWWF	B 	
j^<<	%  " Fb'#+CGJr7WDHHUO''M	B$	A
CuHL"**%))J
$
<	 ::CQ$$ BZK))...*#tyy)*=c"gRXX.Rvvb"~AaKF
#Bvv}}RVVBZ(H4}?'E67CB U2T2BaKF UU5\$$&B66%$DD*A
N*E !TENQ.ED[FVe^#E&2+B66"b>D4KEC%%-'EFADA $F(CQ$$b	%)!VRS*2LRP :FBHlE "
fNN2	Q,rx@$X/BCCQ##		v15_ $
d 88H-!8!8Q 677i(C  )   	%	 ::CQ$$	%s   P7 7QQc                 h    UUUS.n[        XU4U40 UD6n	U(       a  U	S   U	S   U	S   U	S   4$ U	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x2rH   r   r   r   r   optionsrb   s
             r@   r   r   m  sW    f  G #4b4
C7
CC3xUS]CK??3xrC   c           
      Z   [        U5        Un[        U5      S:w  a  [        S5      eUu  p[        U5      (       a  [        U	5      (       d  [        S5      eX:  a  [        S5      eSn
SnSn[	        S5      nS	S
[	        S5      -
  -  nXnnXUU-
  -  -   nUUnnS=nnUnU " U/UQ76 nSnSUU4n[
        R                  nU=nnS	UU-   -  nU[
        R                  " U5      -  US
-  -   nSU-  nUS:  a(  [        S5        [        U5        [        SUU4-   -  5        [
        R                  " UU-
  5      US	UU-
  -  -
  :  GaP  Sn [
        R                  " U5      U:  a  Sn UU-
  UU-
  -  n!UU-
  UU-
  -  n"UU-
  U"-  UU-
  U!-  -
  n#SU"U!-
  -  n"U"S:  a  U#* n#[
        R                  " U"5      n"Un!Un[
        R                  " U#5      [
        R                  " S	U"-  U!-  5      :  aa  U#U"UU-
  -  :  aU  U#U"UU-
  -  :  aI  U#S-   U"-  nUU-   nSnUU-
  U:  d	  UU-
  U:  a'  [
        R                  " UU-
  5      UU-
  S:H  -   n$UU$-  nOSn U (       a  UU:  a  UU-
  nOUU-
  nUU-  nSn[
        R                  " U5      US:H  -   n$UU$[
        R                  " [
        R                  " U5      U5      -  -   nU " U/UQ76 nUS-  nUUU4nUS:  a  [        SUU4-   -  5        UU::  a  UU:  a  UnOUnUUnnUUnnUUnnO6UU:  a  UnOUnUU::  d  UU:X  a	  UUnnUUnnOUU::  d  UU:X  d  UU:X  a  UUnnS	UU-   -  nU[
        R                  " U5      -  US
-  -   nSU-  nUU:  a  Sn
O)[
        R                  " UU-
  5      US	UU-
  -  -
  :  a  GMP  [
        R                  " U5      (       d6  [
        R                  " U5      (       d  [
        R                  " U5      (       a  Sn
Un%US:  a  [        UU
U%XsU5        [        U%XS:H  SS[        S   S.R                  U
S5      UUUS9n&U&$ )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  r   r   r   rE   r   r   r%  signmaximumr  	_endprintr   r$  get)'r   r   rH   r   r2   r   r   r   r  r  flagheaderr\  sqrt_epsgolden_meanar  fulcnfcxfratr   r>   r   num	fmin_datafuffulcfnfcr   tol1tol2r	   r   qr   sirE  rG  s'                                          r@   r  r    s   . ?+F
6{a9::FBR  %5b%9%9FGG	wCDDDAFDG}HtCy)KqAa!e$$DDCMC!
A	a$B
CBI	BED	ABbffRj 53;.D:Daxc
f(I,?@A66"r'?dSAE]2366!9tFcb5j)AdrDy)Ada28q.0Aq1uA3wBq	AAA RVVCE!G_,1q!b&z>a"f%3w!mH)UdNQ$b)b2g!^<B)CRxFFa-C"DWWS\SAX&bjjd333!^d^q!RL	!8,	TG0CDE8Bwt%DBCB2vd
r	!4erTT+42:43;eAE]"&&*$us{2Tz&=DK 66"r'?dSAE]23N 
xx||rxx||rxx||Dax!T45TAI(9)3(7(>%@ ADD" s5F MrC   c                   B    \ rS rSr  S	S jrS
S jrS rS rSS jrSr	g)Brentia	  c                     Xl         X l        X0l        X@l        SU l        SU l        S U l        S U l        SU l        SU l	        X`l
        g )Ngdy=gŋ!r?r   )r   rH   tolr2   _mintol_cgxminrE  iterfuncallsr   )r?   r   rH   r  r2   r   r   s          r@   rA   Brent.__init__c	  sE    						rC   Nc                     Xl         g r:   )brack)r?   r  s     r@   set_bracketBrent.set_bracketr	  s    
rC   c                    U R                   nU R                  nU R                  nUc  [        XS9u  pEpgpn
O[	        U5      S:X  a  [        XS   US   US9u  pEpgpn
On[	        U5      S:X  aT  Uu  pEnXF:  a  XFpFXE:  a  XV:  d  [        S5      eU" U4U-   6 nU" U4U-   6 nU" U4U-   6 n	X:  a  X:  d  [        S5      eSn
O[        S	5      eXEXgXU
4$ )
NrH   r   r   r!   xaxbrH   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   rH   r  r
   r  r   )r?   r   rH   r  r  r  r@  fafbr  r  s              r@   get_bracket_infoBrent.get_bracket_infou	  s   yyyy

 =/6t/G,BBBHZ1_/6ta:?(0O,BBBHZ1_JBBBW27 I  &B&B&BW27 M 
 H 7 8 8 rrx//rC   c                    U R                   nU R                  5       u  p#pEpgnU R                  n	U R                  n
U=n=pU=n=nnX$:  a  UnUnOUnUnSnSnU R                  S:  a7  [        S5        [        SS SSS SSS	 35        [        US
 SUS SUS 35        UU R                  :  GaC  U R                  [        R                  " U5      -  U	-   nSU-  nSUU-   -  n[        R                  " UU-
  5      USUU-
  -  -
  :  a  GO[        R                  " U5      U::  a  UU:  a  UU-
  nOUU-
  nU
U-  nOX-
  UU-
  -  nX-
  UU-
  -  nX-
  U-  X-
  U-  -
  nSUU-
  -  nUS:  a  U* n[        R                  " U5      nUnWnUUUU-
  -  :  ao  UUUU-
  -  :  ac  [        R                  " U5      [        R                  " SU-  U-  5      :  a/  US-  U-  nUU-   nUU-
  U:  d	  UU-
  U:  a  UU-
  S:  a  UnOU* nOUU:  a  UU-
  nOUU-
  nU
U-  n[        R                  " U5      U:  a  US:  a  UU-   nOUU-
  nOUU-   nU" U4U R                  -   6 nUS-  nUU:  a4  UU:  a  UnOUnUU::  d  X:X  a	  UnUnUnUnO,UU::  d
  X:X  d  X:X  a  UnUnOUU:  a  UnOUnUnUnUnUnUnUnU R                  S:  a  [        US
 SUS SUS 35        US-  nUU R                  :  a  GMC  Xl        UU l        UU l        Xl        g )Nr  r   r   r  
Func-count^12r>   f(x) ^12^12g^12.6gr   r  r   r!   )r   r  r  r   r   r%  r2   r  rE   r   rH   r  rE  r  r  )r?   r   r  r  r@  r  r  r  r  r  r   r>   rS  rT  fwfvr   r  r  deltaxr  r  r  xmidr  tmp1tmp2r   dx_tempur  s                                  r@   optimizeBrent.optimize	  s   yy+/+@+@+B(,,hh AR"GAAAA99q=#J\#&aCy&?@XdO1QvJa6{;<dll"88bffQi''1D:D!a%=Dvva$h4#Q-#78 v$&IUFUFFl"r'*"r'*UdNaet^3dTk*3JAvvd| Q'a$!a%..@RVVC$J,@%AAc'D.CCAQ$1q5D.!8q="&C#'%CT	!"Q!"Q,Csd"!8DADAGtyy(*BMHREAA"H!&AABBBhAFABFAAyy1}$q6
!Bv;?@AIDc dll"l 			 rC   c                     U(       a.  U R                   U R                  U R                  U R                  4$ U R                   $ r:   )r  rE  r  r  )r?   r   s     r@   
get_resultBrent.get_result
  s.    99diiDMMAA99rC   )r   r  rH   r  r   r   r  rE  r  r2   r  r  )rY   `sbO>  r   r   r:   )F)
rS   rT   rU   rV   rA   r  r  r$  r'  rX   rY   rC   r@   r  r  a	  s$    ;>%&$0Lr!hrC   r  c                 b    UUS.n[        XU40 UD6nU(       a  US   US   US   US   4$ U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   rH   r  r  r   r2   r  rb   s           r@   r   r   
  sN    N !#G
 d
>g
>C3xUSZV<<3xrC   c           	      <   [        U5        UnUS:  a  [        SU< 35      e[        XUSXES9nUR                  U5        UR	                  5         UR                  SS9u  ppX:  =(       a8    [        R                  " U	5      =(       d    [        R                  " U
5      (       + nU(       a  SU S3nOGX:  a  Sn[        R                  " U	5      (       d  [        R                  " U
5      (       a
  [        S	    nU(       a  [        U(       + W5        [        XXUWS
9$ )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   rH   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   r   r  r  r$  r'  rE   r  r$  r  r   )r   r  rH   r   r2   r   r   r  r   r>   rE  r   r   r0   r
  s                  r@   r-  r-  f
  s    6 ?+
C
Qw9#ABBtC"G@E	e	NN))d);ASmCRXXa[%BBHHTN CG$$(6- >?G88A;;"((4..(/0G&7{G<dS")7< <rC   i  c                 X    X5S.n[        XU40 UD6nU(       a  US   US   US   4$ U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	   
  sC    J /G
!$t
?w
?C3xUS[003xrC   c           	         [        U5        UnUc  [        XS9u  pppnO[        U5      S:X  a  [        XS   US   US9u  pppnOn[        U5      S:X  aT  Uu  pn
X:  a  XpX:  a  X:  d  [        S5      eU " U4U-   6 nU " U	4U-   6 nU " U
4U-   6 nX:  a  X:  d  [        S5      eSnO[        S	5      eS
nSU-
  nU
nUn[        R
                  " X-
  5      [        R
                  " X-
  5      :  a  U	nU	UX-
  -  -   nOU	nU	UX-
  -  -
  nU " U4U-   6 nU " U4U-   6 nUS-  nSnUS:  a!  [        S5        [        SS SSS SSS 35        [        U5       H  n[        R
                  " UU-
  5      U[        R
                  " U5      [        R
                  " U5      -   -  ::  a    OtUU:  a  UnUnUU-  UU-  -   nUnU " U4U-   6 nOUnUnUU-  UU-  -   nUnU " U4U-   6 nUS-  nUS:  a%  UU:  a  UUnnOUUnn[        US SUS SUS 35        US-  nM     UU:  a  UnUnOUnUnUU:  =(       a8    [        R                  " U5      =(       d    [        R                  " U5      (       + nU(       a  SU S3nOHUU:  a  Sn[        R                  " U5      (       d  [        R                  " U5      (       a
  [        S    nU(       a  [        U(       + W5        [        UUUUUWS9$ )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.
r
  r   r   r!   r  r   r  r  r  gz7?r   r  r  r  r>   r  r  r  r  r0  r1  r2  r4   r;   r   r>   r   r0   r
  )r   r
   r  r   rE   r   r%  r  r  r$  r  r   )r   r  rH   r   r2   r   r   r  r  r  r@  r  r  r  r  _gR_gCx3r   r  r  re  rf  r   r  r  rE  r0   r
  s                                r@   r4  r4  
  s]   * ?+
C}+24+C(	Uq+24!H6;AhT,K(	Uq
GrwE  REDL"REDL"REDL"rwI  NOO
C
)C	B	B
rw"&&/)#/!#/!		B		BMH
Caxc
c"!C9AfT];<7^66"r'?cRVVBZ"&&*%<==GBBrC"H$BB&BBBrC"H$BB&BA!8RdddXdO1T&M4-@Aq/ 4 	RGmFRXXd^%Erxx~ FG$$(6- '>?G88D>>RXXd^^(/0G&7{G<dTs")7< <rC   c                    SnSn[         R                  " X/5      u  pU " U4U-   6 nU " U4U-   6 n	X:  a  X!p!XpX&X!-
  -  -   n
U " U
4U-   6 nSnSnX:  GaM  X!-
  X-
  -  nX*-
  X-
  -  nX-
  n[         R                  " U5      U:  a  SU-  nOSU-  nX"U
-
  U-  X!-
  U-  -
  U-  -
  nX$X-
  -  -   nSnX:  a  [        U5      eUS-  nUU
-
  UU-
  -  S:  a@  U " U4U-   6 nUS-  nUU:  a	  UnUnU	nUn	OUU	:  a  Un
UnOXX-
  -  -   nU " U4U-   6 nUS-  nOzUU-
  UU
-
  -  S:  a  UnU " U4U-   6 nUS-  nOZUU-
  U
U-
  -  S:  a4  U " U4U-   6 nUS-  nUU:  a  U
nUn
XX-
  -  -   nUn	UnU " U4U-   6 nUS-  nOXX-
  -  -   nU " U4U-   6 nUS-  nUnU
nUn
U	nUn	UnX:  a  GMM  X:  =(       a    X:*  =(       d    X:  =(       a    X:*  nXs=:  =(       a    U
:  Os  =(       d    Xs=:  =(       a    U:  Os  n[         R                  " U5      =(       a3    [         R                  " U5      =(       a    [         R                  " U
5      nS	nU(       a  U(       a  U(       d  [        U5      nXXXU4Ul        UeXXXU4$ )
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.)rE   r   r   RuntimeErrorr   BracketErrordata)r   r  r  rH   
grow_limitr2   _gold_verysmall_numr  r  r@  r  r  r  r   r!  valdenomrS  wlimr   r  cond1cond2cond3r   s                             r@   r
   r
   d  s.   T ENZZ!FB	ut|	B	ut|	B
BB	rw	B		BHD7BG$BG$k66#;'.(E#IE7d"bg%55>>"'**' >s##	FrAv$t%BMHRr'bg&&At%BMH$h#s*At%BMH$ha 3&t%BMHR"'**QD4K)Abg&&At%BMHq 7v W!<rw';28E\\r\)R\\r\EKKOCBCBKKOE7Ce""(3228++rC   c                       \ rS rSrSrg)r<  i  rY   Nry   rY   rC   r@   r<  r<    rz   rC   r<  c           
          U " XU40 UD6nU$ ! [          a  n[        U5      nUR                  u  pppnXU
/XU/nn[        R                  " [        R
                  " UU/5      5      (       a!  [        R                  [        R                  nnO [        R                  " U5      nUU   UU   nn[        XUSSUS9s S nA$ S nAff = f)Nr   Fr6  )	r<  r   r=  rE   r   r  r4   r   r   )solverr;   r
   rH   r  rb   r   r   r  r  r@  r  r  r  r  xsfsr>   imins                      r@   _recover_from_bracket_errorrM    s    $AS4373 J  
A!f+,66("|B66"((B8$%%VVRVVsAs99R=DXr$xsA#"#UCA 	A
As   
 
CB"C :C Cc                    UR                  5       u  nX$   X4   p2X   X   pX -
  U-  nX0-
  U-  nUS:  n[        R                  " XuS5      n[        R                  " USU5      n	[        R                  " XvS5      n
[        R                  " USU5      n[        R                  " X-   5      n[        R                  " X-   5      nX:  a  X4$ S$ )aW  
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   )nonzerorE   r  r  r#  )r   r  r.  r/  rO  lowhighposlmin_poslmin_neglmax_poslmax_neglminlmaxs                 r@   _line_for_searchrY  )  s    L }}HG*3[5IU^u
$C%D !)Cxx!$HxxQ%Hxx1%HxxQ$H66(%&D66(%&D  <D<3V3rC   c                 l  ^ ^^^ U UU4S jm[         R                  " T5      (       d  Ub  UTT4$ T " T5      TT4$ Uc@  Uc=  [        [        TS[	        5       US9nUR
                  UR                  pUT-  mU	TT-   T4$ [        TTXE5      n
[         R                  " U
S   5      (       a*  [         R                  " U
S   5      (       a  [        T TTXcS9$ [         R                  " U
S   5      (       dL  [         R                  " U
S   5      (       d.  [        TXS-  S9nUR
                  T-  mUR                  TT-   T4$ [         R                  " U
S   5      [         R                  " U
S   5      4n
[        U4S	 jU
US-  S9n[         R                  " UR
                  5      T-  mUR                  TT-   T4$ )
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                     > T" TU T-  -   5      $ r:   rY   )r  r   r   xis    r@   myfunc"_linesearch_powell.<locals>.myfunc}  s    AbL!!rC   N)r   r   r!   )rE  r  d   )r   c                 <   > T" [         R                  " U 5      5      $ r:   )rE   tan)r>   r]  s    r@   <lambda>$_linesearch_powell.<locals>.<lambda>  s    &+rC   )rE   r   rM  r-  tupler>   r;   rY  isneginfisposinf_linesearch_powellr  arctanra  )r   r   r\  r  r.  r/  rE  rb   	alpha_minfretboundr]  s   ```        @r@   rg  rg  h  s   *" 66"::!%!1q"HQB7GH		!4)*@*0$cK%%4^QVR BA;;uQx  R[[q%:%:%dArFFU1X&&r{{58/D/D*65c	JCB77AFB&&
 IIeAh'58)<<E*+Ci!C #B77AFB&&rC   c                     UUUUUUU	S.n[        U
5      n
[        XU4SU
0UD6nU(       a+  US   US   US   US   US   US   4nU	(       a  XS	   4-  nU$ U	(       a
  US   US	   4$ U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   rc   r>   r;   rm  r   r   r   r   )rt   _minimize_powell)r   r   rH   r   r   r2   r   r   r   r   rc   rm  r   rb   r  s                  r@   r   r     s    l  "D h'H
4T
EH
E
ECs8SZWs5zv;H/I))Gs8S^++s8OrC   c                 	   [        U5        UnUn[        U5      R                  5       nU(       a  U/n[        U5      nUc  Uc  US-  nUS-  nO[Uc+  U[        R
                  :X  a  US-  nO>[        R
                  nO-Uc*  U[        R
                  :X  a  US-  nO[        R
                  n[        XU5      u  nn U
c  [        U[        S9n
OX[        U
[        S9n
[        R                  R                  U
5      U
R                  S   :w  a  [        R                  " S[        SS9  Uc  Su  nnOnUR                  UR                   nn[        R"                  " UU:  5      (       d  [        R"                  " UU:  5      (       a  [        R                  " S[        SS9  U " U5      nUR%                  5       nSn  UnSnS	n['        U5       H1  nU
U   nUn[)        XUUS
-  UUUS9u  nnnUU-
  U:  d  M*  UU-
  nUnM3     US-  nU(       a  WR+                  U5        [-        UUS9n[/        UU5      (       a  GOMU[        R0                  " U5      [        R0                  " U5      -   -  S-   nSUU-
  -  U::  a  GOUS   U:  a  GOUU:  a  O[        R2                  " U5      (       a  [        R2                  " U5      (       a  OUU-
  nUR%                  5       nUc  Uc  Sn O[5        UUUU5      u  n!n U[7        U S5      U-  -   n"U " U"5      nUU:  aq  SUU-   SU-  -
  -  n#UU-
  U-
  n$U#U$U$-  -  n#UU-
  n$U#UU$-  U$-  -  n#U#S	:  a=  [)        XUUS
-  UUUS9u  nnn[        R"                  " U5      (       a  U
S   U
U'   UU
S'   GM  Sn%[:        S   n&U(       aH  [        R"                  " UU:  5      (       d  [        R"                  " UU:  5      (       a  Sn%[:        S   n&OvUS   U:  a  Sn%[:        S   n&OaUU:  a  Sn%[:        S   n&OO[        R2                  " U5      (       d)  [        R2                  " U5      R#                  5       (       a  Sn%[:        S   n&U	(       a?  [=        U%U&[>        5        [A        SUS 35        [A        SU-  5        [A        SUS   -  5        [-        UU
UUS   U%U%S:H  U&US9n'U(       a  WU'S'   U'$ ! [8         a     GMH  f = f)aU  
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.
  r   r   zBdirec input is not full rank, some parameters may not be optimizedr   r   )NNr  r  r_  )r  r.  r/  rE  r!   r  g#B;r   r   r0   r   r5   r1   r   r2   r4   r  r  r  r	  )r;   rm  r   r   r   r0   r
  r>   r   )!r   r   r  r  rE   r   r   r   r  r  matrix_rankr   r   r   r   r  r  r   rG   r  rg  r   r   r*   r   r  rY  r#  r   r$  r  r   r%  )(r   r   rH   rc   r   r   r   r2   r1   r   rm  r   r   r   r   r>   r   r0  r7  r.  r/  rE  r  r  r   biginddeltar  direc1fx2r_   bndrX  _r  ttemprF  r   rG  s(                                           r@   rn  rn  /  s   x ?+FFA#AA6>d(T	 RVV$hGffG	bffXFVVF ;4vNLFD}AU#U+99  '5;;q>9MM -)a9 ~
 $. [ $*99fii[66+"##rvvb;.>'?'?MML)a9 7D	
BD
=	BFE1Xq"4Tf9=ALAL:>	#@a
 $J%'$JEF  AIDq!"01$"?(3FGG"&&*rvvd|34u<Cb4i C'ayF"wxx|| VFB"{':*1fk;O4Sq\F**Br(CScCH,-T	E)T$YCxU4Z_$s7&8 3J$/$/!'OD!V vvf~~(-b	f$*b	y @ H
)
$C
 266+/**bffQ_.E.Eo.	f	h'	i(	$288A;??,,e$&xnE1$q:;'$./1F1I=>Et&)#+h!m$'1.F #yMA ! 		s8   67R= 1AR= 6?R= 7	R= R= 	6R=  C R= =
SSc                     US:X  a  US:  a  [        SUS5        g US:X  a  SnOUS:X  a  S[        S    3n[        UW5        g )	Nr   r!   r0  )zO
Maximum number of function evaluations exceeded --- increase maxfun argument.
r   
r4   )r%  r$  r  )r>   r  rE  r   r   r   r   s          r@   r  r  !  s[    qy!8 #$(#/ 	qy-	?5)*+"4-
rC   r  c           	         [        U5      nUS:  a  [        S5      e[        U5      n	[        U5       HU  n
[	        X   [
        5      (       a  M  [        X   5      S:  a  [        X   5      [        U5      4-   X'   [        X   6 X'   MW     US:X  a  U	S   n	[        R                  U	   nUR                  nUS:  a<  [        R                  " XS   [        R                  " USS 5      45      R                  n[        R                  " U5      (       d  U4n[        X5      n[!        US9 n[        R"                  " [        U" X5      5      5      nUS:X  a  U4n[        R$                  " U5      nO@US:  a:  [        R                  " XSS 5      n[        R                  " UR                  U5      nSSS5        [        W5      n['        UR)                  5       SS	9n[        R*                  " U[,        5      n[        R*                  " U[.        5      n[        US-
  SS5       H  n
UU
   nUUU
   -  UU
'   UU-  nM     [        U5       H  n
X   [        U5         UU
'   M     U[        U5         nUS:X  a
  US   nUS   n[1        U5      (       a  [3        U5      R4                  n[7        5       nS
U;   a  SUS
'   SU;   a  UUS'   OSU;   a  SU0US'   U" U U4SU0UD6n[	        U[8        5      (       a%  UR:                  nUR<                  nUR>                  nOUS   nUS   nUS   S:H  nU(       d!  U(       a  [@        RB                  " S[D        SS9  U(       a  UUX4$ U$ ! , (       d  f       GN= f)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  rH   zhEither final optimization did not succeed or `finish` does not return `statuscode` as its last argument.r   r   )#r  r   r  r  r  slicerd  complexrE   mgridr   reshapeprodTiterable_Brute_Wrapperr'   r  r  r   r  r  r  r  r   _getfullargspecrH   dictr   r>   r;   r0   r   r   r   )r   rangesrH   Nsr   finishr   workersr0  lranger2  grid
inpt_shapewrapped_funcmapperJoutNshapeindxNindxr  thisNJminfinish_argsfinish_kwargsrb   r0   s                             r@   r   r   3  s4   Z 	FA2v . / 	/&\F1X&)U++69~!!&),~=	vy)FI	 
 	
Q88FD J	Azz$A
120G HIKK;;tw!$-L 
	!VxxVL789F7D::d#D!e::dqrN3D::dffj1D 
" 4[F$**,R(DHHQE88AuD1q5"b!q	&)#au} " 1X'%,'Q  eD	QAwAw%f-22K'+,M-([ $(M&!+% )/~M)$ T4<d<m<c>**55D77DkkGq6Dq6D"glG S,< T4%%w 
"	!s   *BM!!
M0c                   $    \ rS rSrSrS rS rSrg)r  i8  zM
Object to wrap user cost function for optimize.brute, allowing picklability
c                 4    Xl         Uc  / U l        g UU l        g r:   )r  rH   )r?   r  rH   s      r@   rA   _Brute_Wrapper.__init__=  s    ,B	D	rC   c                     U R                   " [        R                  " U5      R                  5       /U R                  Q76 $ r:   )r  rE   r   r  rH   )r?   r>   s     r@   rN   _Brute_Wrapper.__call__A  s+    vvbjjm++-:		::rC   )rH   r  N)rS   rT   rU   rV   rW   rA   rN   rX   rY   rC   r@   r  r  8  s    1;rC   r  c           	      2   SSK nSSSSSSS	.nU c  / S
QnUR                  [        SSS95        UR                  / SQ5        UR                  [        SSS95        UR                  / SQ5        UR                  [        SSS95        UR                  / SQ5        UR                  [        SSS95        SR	                  U5      nGO?U R                  5       n X;  a  [        SU < 35      eUcb  / nX@    HF  u  pgUR                  SU-   SS[        U5      -  -   S-   /5        UR                  [        XSS95        MH     SR	                  U5      nOUR                  5       n[        X@   5      nX;  a  [        SU< 35      eX   nUR                  S5      n	SR	                  U	SS 5      n
[        U
5        [        [        R                  U
   U	S   5      nUR                  nUb   UR                  U5      R!                  5       nOSnU(       a  [#        U5        gU$ )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)r]   z*scipy.optimize._cobyla_py._minimize_cobyla)r^   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)r\   z(scipy.optimize._slsqp_py._minimize_slsqp)r[   z!scipy.optimize._tnc._minimize_tnc)z	trust-ncgz3scipy.optimize._trustregion_ncg._minimize_trust_ncg)rf   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

r|  =zUnknown method .r   )textwrapr   r   extendr   lowerr   r  r  split
__import__getattrsysmodulesrW   dedentstripr%  )rI  rr   r   r  doc_routinestextnamerw  methodspartsmod_nameobjdocs                r@   r   r   F  s   V 
,
	

!

s>L@ ~?L%89 * 	+L!2?@  	 Le45 " 	#L78wwt}%vj9::>D'/Vd]D3s4y=,@6,IJKLEBC 0 774=D\\^F</0G$ ?6*!=>>?D JJsOExxcr
+Hx #++h/r;C ++Cs+113drC   r:   )r   )NrY   NNNN)
rY   r   r   NNr   r!   r   NN)rY   NNNFFNr   r   FN)rY   r}  r*  r   r!   )rY   r}  r*  r   )rY   Nr)  r   r*  )NrY   r)  r*  r   )r  r   rY   g     [@rp  )gMbP?NNN)
rY   NNr   r   NNFNF)NNT)e__all____docformat__r  r   r  rm   numpyr   r   r   r   r   r   rE   scipy.linalgr   r   r   scipy.sparse.linalgr    _linesearchr"   r#   r   r$   _numdiffr%   scipy._lib._utilr&   r  r'   r(   r)   r*   r+   (scipy.optimize._differentiable_functionsr,   r-   scipy._lib._array_apir.   
scipy._libr/   r   r$  r7   rt   r   UserWarningr   r   r   r   r  r  r  _epsilonr   r   r   r   r   r   r   r   r   r;  r   r   r   r   r   r   rg  ri  r|  r   r   r  r  r   r  r   r  r   r  r  r   r-  r	   r4  r
   r<  rM  rY  rg  r   rn  r  r   r  r   rY   rC   r@   <module>r     st  ( &   
  : :  ; ; .- - ( FM M O 1 - F/*33%.	/ 60*	[ *	Z	k 	LW. ##$; AE@D"&[|
0f'T(4V*Z$0	 	$6 HLIMzz 6:9>;?HLL^ "* N/b F+.6TZ ,Zz	| 	*Z !r266!!Q4CM` "$266x%dt!	nbJ Rdd!dstn  "tdXtDSWt %)2tt1tup &(TD $4Xt!ey!x 8;"#[| 13;<Slr rjM` <C-.6<r ($JZ )-2!)4au<p\,~	< 	D<4~ )-@D6'r BFGKK\ ?C@D8=od$  BAdaBJ; ;]rC   