
    (ph                     r   S r SS/rSSKJr  SSKrSSKJrJrJ	r	J
r
JrJrJrJrJrJrJrJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJ r   SSK!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,J-r-J.r.J/r/  SSK0J1r1  / SQr2/ SQr3/ SQr4   S S jr5  S!S jr6S r7S"S jr8S r9S r:S r;S r< S#S jr=g)$z
Unified interfaces to minimization algorithms.

Functions
---------
- minimize : minimization of a function of several variables.
- minimize_scalar : minimization of a function of one variable.
minimizeminimize_scalar    )warnN   )_minimize_neldermead_minimize_powell_minimize_cg_minimize_bfgs_minimize_newtoncg_minimize_scalar_brent_minimize_scalar_bounded_minimize_scalar_golden
MemoizeJacOptimizeResult_wrap_callback_recover_from_bracket_error)_minimize_dogleg)_minimize_trust_ncg)_minimize_trust_krylov)_minimize_trustregion_exact)_minimize_trustregion_constr)_minimize_lbfgsb)_minimize_tnc)_minimize_cobyla)_minimize_cobyqa)_minimize_slsqp)old_bound_to_newnew_bounds_to_oldold_constraint_to_newnew_constraint_to_oldNonlinearConstraintLinearConstraintBoundsPreparedConstraint)
FD_METHODS)nelder-meadpowellcgbfgs	newton-cgl-bfgs-btnccobylacobyqaslsqptrust-constrdogleg	trust-ncgtrust-exacttrust-krylov)r&   r'   r(   r)   r*   r+   r0   r1   r2   r3   r4   r.   )brentboundedgoldenc                    [         R                  " [         R                  " U5      5      nUR                  S:w  a  [	        S5      eUR
                  R                  [         R                  S   ;   a  [         R                  " U[        S9n[        U[        5      (       d  U4nUc  U(       a  SnOUb  SnOSn[        U5      (       a  S	nOUR                  5       nUc  0 nUS
;   a#  [        U5      (       a  [        SU S3[        SS9  US;  a  Ub  [        SU S3[        SS9  US;  a  Ub  [        SU S3[        SS9  US;  a.  [         R                   " U5      (       a  [        SU S3[        SS9  US;  a  Ub  [        SU S3[        SS9  US;   a*  UR#                  SS5      (       a  [        SU S3[        SS9  [        U5      (       a  OMUSL a  [%        U 5      n U R&                  nO0U[(        ;   a  US;   a  OUS;   a  SnOUb  [        U5      SL a  SnOSnU	b  [+        U5      nUS:X  a$  UR-                  S U	5        UR-                  S!U	5        US";   a  UR-                  S#U	5        US$;   a  UR-                  S%U	5        US&;   a  UR-                  S'U	5        US(;   a  UR-                  S)U	5        US*:X  a  UR-                  S+U	5        US,:X  a6  UR-                  S#U	5        UR-                  S'U	5        UR-                  S-U	5        US	:X  a  U" X4X$XVXxU
S..UD6$ [/        XU5      nSnUGb  [1        XqS/5      n[3        XqU5      nUS0;   Ga{  UR4                  UR6                  :H  n[         R8                  " U5      (       a  [;        XXUS19$ [        U5      (       + nU H'  n[        UR#                  S2S5      5      (       a  M%  SnM)     UR!                  5       =(       a    U=(       d    US3:H  nU(       a  UR4                  U   nX)    n[=        X~5      n[?        XU5      n [        U
5      (       a  [?        XU5      n
[        U5      (       a  [?        XNUSS49nU Vs/ s H  nURA                  5       PM     nnU HK  n[?        US5   UUSS6S79US5'   [        UR#                  S2S5      5      (       d  M8  [?        US2   UUSSS79US2'   MM     [1        XqU5      n[C        X5      n
US:X  a  [E        XX*4S8U0UD6nGOLUS9:X  a  [G        XX*U40 UD6nGO6US::X  a  [I        XX$U
40 UD6nGO US;:X  a  [K        XX$U
40 UD6nGO
US<:X  a  [M        XX$XVU
40 UD6nOUS=:X  a  [O        XX$U4S>U
0UD6nOUS3:X  a  [Q        XX$U4S>U
0UD6nOUS?:X  a  [S        XX(4U
US@.UD6nOUS*:X  a  [U        XX'X40 UD6nOUSA:X  a  [W        XX$UU4S>U
0UD6nOUS,:X  a  [Y        XX$XVXx4S>U
0UD6nOjUSB:X  a  [[        XX$U4S>U
0UD6nOSUSC:X  a  []        XX$XV4S>U
0UD6nO<USD:X  a  [_        XX$XV4S>U
0UD6nO%USE:X  a  [a        XX$U4S>U
0UD6nO[	        SFU 35      eU(       aS  [c        URd                  WW5      Ul2        [c        URf                  U[         Rh                  5      Ul3        SGU;   a  SUl5        [m        U
SHS5      (       a  SUl7        SIUl8        SJUl9        U$ s  snf )KaZ  Minimization of scalar function of one or more variables.

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.

    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.
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
    Type of solver.  Should be one of

    - 'Nelder-Mead' :ref:`(see here) <optimize.minimize-neldermead>`
    - 'Powell'      :ref:`(see here) <optimize.minimize-powell>`
    - 'CG'          :ref:`(see here) <optimize.minimize-cg>`
    - 'BFGS'        :ref:`(see here) <optimize.minimize-bfgs>`
    - 'Newton-CG'   :ref:`(see here) <optimize.minimize-newtoncg>`
    - 'L-BFGS-B'    :ref:`(see here) <optimize.minimize-lbfgsb>`
    - 'TNC'         :ref:`(see here) <optimize.minimize-tnc>`
    - 'COBYLA'      :ref:`(see here) <optimize.minimize-cobyla>`
    - 'COBYQA'      :ref:`(see here) <optimize.minimize-cobyqa>`
    - 'SLSQP'       :ref:`(see here) <optimize.minimize-slsqp>`
    - 'trust-constr':ref:`(see here) <optimize.minimize-trustconstr>`
    - 'dogleg'      :ref:`(see here) <optimize.minimize-dogleg>`
    - 'trust-ncg'   :ref:`(see here) <optimize.minimize-trustncg>`
    - 'trust-exact' :ref:`(see here) <optimize.minimize-trustexact>`
    - 'trust-krylov' :ref:`(see here) <optimize.minimize-trustkrylov>`
    - custom - a callable object, see below for description.

    If not given, chosen to be one of ``BFGS``, ``L-BFGS-B``, ``SLSQP``,
    depending on whether or not the problem has constraints or bounds.
jac : {callable,  '2-point', '3-point', 'cs', bool}, optional
    Method for computing the gradient vector. Only for CG, BFGS,
    Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg, trust-krylov,
    trust-exact and trust-constr.
    If it is a callable, it should be a function that returns the gradient
    vector::

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

    where ``x`` is an array with shape (n,) and ``args`` is a tuple with
    the fixed parameters. If `jac` is a Boolean and is True, `fun` is
    assumed to return a tuple ``(f, g)`` containing the objective
    function and the gradient.
    Methods 'Newton-CG', 'trust-ncg', 'dogleg', 'trust-exact', and
    'trust-krylov' require that either a callable be supplied, or that
    `fun` return the objective and gradient.
    If None or False, the gradient will be estimated using 2-point finite
    difference estimation with an absolute step size.
    Alternatively, the keywords  {'2-point', '3-point', 'cs'} can be used
    to select a finite difference scheme for numerical estimation of the
    gradient with a relative step size. These finite difference schemes
    obey any specified `bounds`.
hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy}, optional
    Method for computing the Hessian matrix. Only for Newton-CG, dogleg,
    trust-ncg, trust-krylov, trust-exact and trust-constr.
    If it is callable, it should return the Hessian matrix::

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

    where ``x`` is a (n,) ndarray and ``args`` is a tuple with the fixed
    parameters.
    The keywords {'2-point', '3-point', 'cs'} can also be used to select
    a finite difference scheme for numerical estimation of the hessian.
    Alternatively, objects implementing the `HessianUpdateStrategy`
    interface can be used to approximate the Hessian. Available
    quasi-Newton methods implementing this interface are:

    - `BFGS`
    - `SR1`

    Not all of the options are available for each of the methods; for
    availability refer to the notes.
hessp : callable, optional
    Hessian of objective function times an arbitrary vector p. Only for
    Newton-CG, trust-ncg, trust-krylov, trust-constr.
    Only one of `hessp` or `hess` needs to be given. If `hess` is
    provided, then `hessp` will be ignored. `hessp` must compute the
    Hessian times an arbitrary vector::

        hessp(x, p, *args) ->  ndarray shape (n,)

    where ``x`` is a (n,) ndarray, ``p`` is an arbitrary vector with
    dimension (n,) and ``args`` is a tuple with the fixed
    parameters.
bounds : sequence or `Bounds`, optional
    Bounds on variables for Nelder-Mead, L-BFGS-B, TNC, SLSQP, Powell,
    trust-constr, COBYLA, and COBYQA methods. 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.

constraints : {Constraint, dict} or List of {Constraint, dict}, optional
    Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr.

    Constraints for 'trust-constr' and 'cobyqa' are defined as a single object
    or a list of objects specifying constraints to the optimization problem.
    Available constraints are:

    - `LinearConstraint`
    - `NonlinearConstraint`

    Constraints for COBYLA, SLSQP are defined as a list of dictionaries.
    Each dictionary with fields:

    type : str
        Constraint type: 'eq' for equality, 'ineq' for inequality.
    fun : callable
        The function defining the constraint.
    jac : callable, optional
        The Jacobian of `fun` (only for SLSQP).
    args : sequence, optional
        Extra arguments to be passed to the function and Jacobian.

    Equality constraint means that the constraint function result is to
    be zero whereas inequality means that it is to be non-negative.
    Note that COBYLA only supports inequality constraints.

tol : float, optional
    Tolerance for termination. When `tol` is specified, the selected
    minimization algorithm sets some relevant solver-specific tolerance(s)
    equal to `tol`. For detailed control, use solver-specific
    options.
options : dict, optional
    A dictionary of solver options. All methods except `TNC` accept the
    following generic options:

    maxiter : int
        Maximum number of iterations to perform. Depending on the
        method each iteration may use several function evaluations.

        For `TNC` use `maxfun` instead of `maxiter`.
    disp : bool
        Set to True to print convergence messages.

    For method-specific options, see :func:`show_options()`.
callback : callable, optional
    A callable called after each iteration.

    All methods except TNC, SLSQP, and COBYLA support a callable with
    the signature::

        callback(intermediate_result: OptimizeResult)

    where ``intermediate_result`` is a keyword parameter containing an
    `OptimizeResult` with attributes ``x`` and ``fun``, the present values
    of the parameter vector and objective function. Note that the name
    of the parameter must be ``intermediate_result`` for the callback
    to be passed an `OptimizeResult`. These methods will also terminate if
    the callback raises ``StopIteration``.

    All methods except trust-constr (also) support a signature like::

        callback(xk)

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

    Introspection is used to determine which of the signatures above to
    invoke.

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.

See also
--------
minimize_scalar : Interface to minimization algorithms for scalar
    univariate functions
show_options : Additional options accepted by the solvers

Notes
-----
This section describes the available solvers that can be selected by the
'method' parameter. The default method is *BFGS*.

**Unconstrained minimization**

Method :ref:`CG <optimize.minimize-cg>` uses a nonlinear conjugate
gradient algorithm by Polak and Ribiere, a variant of the
Fletcher-Reeves method described in [5]_ pp.120-122. Only the
first derivatives are used.

Method :ref:`BFGS <optimize.minimize-bfgs>` uses the quasi-Newton
method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) [5]_
pp. 136. It uses the first derivatives only. BFGS has proven good
performance even for non-smooth optimizations. This method also
returns an approximation of the Hessian inverse, stored as
`hess_inv` in the OptimizeResult object.

Method :ref:`Newton-CG <optimize.minimize-newtoncg>` uses a
Newton-CG algorithm [5]_ pp. 168 (also known as the truncated
Newton method). It uses a CG method to the compute the search
direction. See also *TNC* method for a box-constrained
minimization with a similar algorithm. Suitable for large-scale
problems.

Method :ref:`dogleg <optimize.minimize-dogleg>` uses the dog-leg
trust-region algorithm [5]_ for unconstrained minimization. This
algorithm requires the gradient and Hessian; furthermore the
Hessian is required to be positive definite.

Method :ref:`trust-ncg <optimize.minimize-trustncg>` uses the
Newton conjugate gradient trust-region algorithm [5]_ for
unconstrained minimization. This algorithm requires the gradient
and either the Hessian or a function that computes the product of
the Hessian with a given vector. Suitable for large-scale problems.

Method :ref:`trust-krylov <optimize.minimize-trustkrylov>` uses
the Newton GLTR trust-region algorithm [14]_, [15]_ for unconstrained
minimization. This algorithm requires the gradient
and either the Hessian or a function that computes the product of
the Hessian with a given vector. Suitable for large-scale problems.
On indefinite problems it requires usually less iterations than the
`trust-ncg` method and is recommended for medium and large-scale problems.

Method :ref:`trust-exact <optimize.minimize-trustexact>`
is a trust-region method for unconstrained minimization in which
quadratic subproblems are solved almost exactly [13]_. This
algorithm requires the gradient and the Hessian (which is
*not* required to be positive definite). It is, in many
situations, the Newton method to converge in fewer iterations
and the most recommended for small and medium-size problems.

**Bound-Constrained minimization**

Method :ref:`Nelder-Mead <optimize.minimize-neldermead>` uses the
Simplex algorithm [1]_, [2]_. This algorithm is robust in many
applications. However, if numerical computation of derivative can be
trusted, other algorithms using the first and/or second derivatives
information might be preferred for their better performance in
general.

Method :ref:`L-BFGS-B <optimize.minimize-lbfgsb>` uses the L-BFGS-B
algorithm [6]_, [7]_ for bound constrained minimization.

Method :ref:`Powell <optimize.minimize-powell>` is a modification
of Powell's method [3]_, [4]_ which is a conjugate direction
method. It performs sequential one-dimensional minimizations along
each vector of the directions set (`direc` field in `options` and
`info`), which is updated at each iteration of the main
minimization loop. The function need not be differentiable, and no
derivatives are taken. 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 (default has full rank), 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.

Method :ref:`TNC <optimize.minimize-tnc>` uses a truncated Newton
algorithm [5]_, [8]_ to minimize a function with variables subject
to bounds. This algorithm uses gradient information; it is also
called Newton Conjugate-Gradient. It differs from the *Newton-CG*
method described above as it wraps a C implementation and allows
each variable to be given upper and lower bounds.

**Constrained Minimization**

Method :ref:`COBYLA <optimize.minimize-cobyla>` uses the
Constrained Optimization BY Linear Approximation (COBYLA) method
[9]_, [10]_, [11]_. The algorithm is based on linear
approximations to the objective function and each constraint. The
method wraps a FORTRAN implementation of the algorithm. The
constraints functions 'fun' may return either a single number
or an array or list of numbers.

Method :ref:`COBYQA <optimize.minimize-cobyqa>` uses the Constrained
Optimization BY Quadratic Approximations (COBYQA) method [18]_. The
algorithm is a derivative-free trust-region SQP method based on quadratic
approximations to the objective function and each nonlinear constraint. The
bounds are treated as unrelaxable constraints, in the sense that the
algorithm always respects them throughout the optimization process.

Method :ref:`SLSQP <optimize.minimize-slsqp>` uses Sequential
Least SQuares Programming to minimize a function of several
variables with any combination of bounds, equality and inequality
constraints. The method wraps the SLSQP Optimization subroutine
originally implemented by Dieter Kraft [12]_. Note that the
wrapper handles infinite values in bounds by converting them into
large floating values.

Method :ref:`trust-constr <optimize.minimize-trustconstr>` is a
trust-region algorithm for constrained optimization. It switches
between two implementations depending on the problem definition.
It is the most versatile constrained minimization algorithm
implemented in SciPy and the most appropriate for large-scale problems.
For equality constrained problems it is an implementation of Byrd-Omojokun
Trust-Region SQP method described in [17]_ and in [5]_, p. 549. When
inequality constraints are imposed as well, it switches to the trust-region
interior point method described in [16]_. This interior point algorithm,
in turn, solves inequality constraints by introducing slack variables
and solving a sequence of equality-constrained barrier problems
for progressively smaller values of the barrier parameter.
The previously described equality constrained SQP method is
used to solve the subproblems with increasing levels of accuracy
as the iterate gets closer to a solution.

**Finite-Difference Options**

For Method :ref:`trust-constr <optimize.minimize-trustconstr>`
the gradient and the Hessian may be approximated using
three finite-difference schemes: {'2-point', '3-point', 'cs'}.
The scheme 'cs' is, potentially, the most accurate but it
requires the function to correctly handle complex inputs and to
be differentiable in the complex plane. The scheme '3-point' is more
accurate than '2-point' but requires twice as many operations. If the
gradient is estimated via finite-differences the Hessian must be
estimated using one of the quasi-Newton strategies.

**Method specific options for the** `hess` **keyword**

+--------------+------+----------+-------------------------+-----+
| method/Hess  | None | callable | '2-point/'3-point'/'cs' | HUS |
+==============+======+==========+=========================+=====+
| Newton-CG    | x    | (n, n)   | x                       | x   |
|              |      | LO       |                         |     |
+--------------+------+----------+-------------------------+-----+
| dogleg       |      | (n, n)   |                         |     |
+--------------+------+----------+-------------------------+-----+
| trust-ncg    |      | (n, n)   | x                       | x   |
+--------------+------+----------+-------------------------+-----+
| trust-krylov |      | (n, n)   | x                       | x   |
+--------------+------+----------+-------------------------+-----+
| trust-exact  |      | (n, n)   |                         |     |
+--------------+------+----------+-------------------------+-----+
| trust-constr | x    | (n, n)   |  x                      | x   |
|              |      | LO       |                         |     |
|              |      | sp       |                         |     |
+--------------+------+----------+-------------------------+-----+

where LO=LinearOperator, sp=Sparse matrix, HUS=HessianUpdateStrategy

**Custom minimizers**

It may be useful to pass a custom minimization method, for example
when using a frontend to this method such as `scipy.optimize.basinhopping`
or a different library.  You can simply pass a callable as the ``method``
parameter.

The callable is called as ``method(fun, x0, args, **kwargs, **options)``
where ``kwargs`` corresponds to any other parameters passed to `minimize`
(such as `callback`, `hess`, etc.), except the `options` dict, which has
its contents also passed as `method` parameters pair by pair.  Also, if
`jac` has been passed as a bool type, `jac` and `fun` are mangled so that
`fun` returns just the function values and `jac` is converted to a function
returning the Jacobian.  The method shall return an `OptimizeResult`
object.

The provided `method` callable must be able to accept (and possibly ignore)
arbitrary parameters; the set of parameters accepted by `minimize` may
expand in future versions and then these parameters will be passed to
the method.  You can find an example in the scipy.optimize tutorial.

References
----------
.. [1] Nelder, J A, and R Mead. 1965. A Simplex Method for Function
    Minimization. The Computer Journal 7: 308-13.
.. [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 (Eds. D F
    Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK.
    191-208.
.. [3] Powell, M J D. 1964. An efficient method for finding the minimum of
   a function of several variables without calculating derivatives. The
   Computer Journal 7: 155-162.
.. [4] Press W, S A Teukolsky, W T Vetterling and B P Flannery.
   Numerical Recipes (any edition), Cambridge University Press.
.. [5] Nocedal, J, and S J Wright. 2006. Numerical Optimization.
   Springer New York.
.. [6] Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory
   Algorithm for Bound Constrained Optimization. SIAM Journal on
   Scientific and Statistical Computing 16 (5): 1190-1208.
.. [7] Zhu, C and R H Byrd and J Nocedal. 1997. L-BFGS-B: Algorithm
   778: L-BFGS-B, FORTRAN routines for large scale bound constrained
   optimization. ACM Transactions on Mathematical Software 23 (4):
   550-560.
.. [8] Nash, S G. Newton-Type Minimization Via the Lanczos Method.
   1984. SIAM Journal of Numerical Analysis 21: 770-778.
.. [9] Powell, M J D. A direct search optimization method that models
   the objective and constraint functions by linear interpolation.
   1994. Advances in Optimization and Numerical Analysis, eds. S. Gomez
   and J-P Hennart, Kluwer Academic (Dordrecht), 51-67.
.. [10] Powell M J D. Direct search algorithms for optimization
   calculations. 1998. Acta Numerica 7: 287-336.
.. [11] Powell M J D. A view of algorithms for optimization without
   derivatives. 2007.Cambridge University Technical Report DAMTP
   2007/NA03
.. [12] Kraft, D. A software package for sequential quadratic
   programming. 1988. Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace
   Center -- Institute for Flight Mechanics, Koln, Germany.
.. [13] Conn, A. R., Gould, N. I., and Toint, P. L.
   Trust region methods. 2000. Siam. pp. 169-200.
.. [14] F. Lenders, C. Kirches, A. Potschka: "trlib: A vector-free
   implementation of the GLTR method for iterative solution of
   the trust region problem", :arxiv:`1611.04718`
.. [15] N. Gould, S. Lucidi, M. Roma, P. Toint: "Solving the
   Trust-Region Subproblem using the Lanczos Method",
   SIAM J. Optim., 9(2), 504--525, (1999).
.. [16] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. 1999.
    An interior point algorithm for large-scale nonlinear  programming.
    SIAM Journal on Optimization 9.4: 877-900.
.. [17] Lalee, Marucha, Jorge Nocedal, and Todd Plantenga. 1998. On the
    implementation of an algorithm for large-scale equality constrained
    optimization. SIAM Journal on Optimization 8.3: 682-706.
.. [18] Ragonneau, T. M. *Model-Based Derivative-Free Optimization Methods
    and Software*. PhD thesis, Department of Applied Mathematics, The Hong
    Kong Polytechnic University, Hong Kong, China, 2022. URL:
    https://theses.lib.polyu.edu.hk/handle/200/12294.

Examples
--------
Let us consider the problem of minimizing the Rosenbrock function. This
function (and its respective derivatives) is implemented in `rosen`
(resp. `rosen_der`, `rosen_hess`) in the `scipy.optimize`.

>>> from scipy.optimize import minimize, rosen, rosen_der

A simple application of the *Nelder-Mead* method is:

>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
>>> res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6)
>>> res.x
array([ 1.,  1.,  1.,  1.,  1.])

Now using the *BFGS* algorithm, using the first derivative and a few
options:

>>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der,
...                options={'gtol': 1e-6, 'disp': True})
Optimization terminated successfully.
         Current function value: 0.000000
         Iterations: 26
         Function evaluations: 31
         Gradient evaluations: 31
>>> res.x
array([ 1.,  1.,  1.,  1.,  1.])
>>> print(res.message)
Optimization terminated successfully.
>>> res.hess_inv
array([
    [ 0.00749589,  0.01255155,  0.02396251,  0.04750988,  0.09495377],  # may vary
    [ 0.01255155,  0.02510441,  0.04794055,  0.09502834,  0.18996269],
    [ 0.02396251,  0.04794055,  0.09631614,  0.19092151,  0.38165151],
    [ 0.04750988,  0.09502834,  0.19092151,  0.38341252,  0.7664427 ],
    [ 0.09495377,  0.18996269,  0.38165151,  0.7664427,   1.53713523]
])


Next, consider a minimization problem with several constraints (namely
Example 16.4 from [5]_). The objective function is:

>>> fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2

There are three constraints defined as:

>>> cons = ({'type': 'ineq', 'fun': lambda x:  x[0] - 2 * x[1] + 2},
...         {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},
...         {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})

And variables must be positive, hence the following bounds:

>>> bnds = ((0, None), (0, None))

The optimization problem is solved using the SLSQP method as:

>>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds,
...                constraints=cons)

It should converge to the theoretical solution (1.4 ,1.7).

r   z"'x0' must only have one dimension.
AllIntegerdtypeNSLSQPzL-BFGS-BBFGS_custom)r&   r'   r-   r.   zMethod z) does not use gradient information (jac).   
stacklevel)r*   r1   r2   r0   r4   r3   r>   z) does not use Hessian information (hess).)r*   r2   r0   r4   r>   z9 does not use Hessian-vector product information (hessp).)r-   r.   r/   r0   r>   z cannot handle constraints.)	r&   r'   r+   r-   r.   r/   r,   r0   r>   z cannot handle bounds.)r+   r,   r-   r.   r/   
return_allFz( does not support the return_all option.T)r0   r)   r(   r+   r,   r/   )r0   z2-pointr&   xatolfatol)r*   r'   r,   xtol)r'   r+   r,   r/   ftol)r)   r(   r+   r,   r1   r2   r3   r4   gtol)r-   r>   tolr.   final_tr_radiusr0   barrier_tol)argsjachesshesspboundsconstraintscallbacknew>   r,   r/   r+   )rK   rP   rL   r,   )removefunr   )min_dimrS   rO   r'   r(   r)   r*   r+   rQ   r-   )rQ   rO   r/   r1   r2   r4   r3   Unknown solver hess_invstop_iterationc   z"`callback` raised `StopIteration`.):np
atleast_1dasarrayndim
ValueErrorr;   kind	typecodesfloat
isinstancetuplecallablelowerboolr   RuntimeWarninganygetr   
derivativer%   dict
setdefaultstandardize_constraintsstandardize_bounds_validate_boundslbuball!_optimize_result_for_equal_bounds_remove_from_bounds_remove_from_funccopyr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   _add_to_arrayxrL   nanrW   getattrsuccessstatusmessage)rT   x0rK   methodrL   rM   rN   rO   rP   rH   rQ   optionsmethremove_varsi_fixed	fd_neededconx_fixedress                      K/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_minimize.pyr   r   5   s   j 
rzz"~	&B	ww!|=>>	xx}}\22ZZ%(dE""w~FFF||~ <<cwvhGH	+  > >BFBRwvhGH	+  / /wvh % %	+ 	LLFF;wvh9:	+ . .282Dwvh45	+ 	@@KKe,,wvhFG	+ }}	onn


L
L	!	!	S	U*  w-= w,w,11vs+99vs+ @ @vs+((uc*80#6>!vs+vs+}c2y c 4D#'4+24 	4 *+4@KK#F6!&d3// yyFII-Gvvg 9k 
 &c]*I"t 455 $I # "++-HY-G$%-K!99g.\,V='g>H%%0GLHC==+C'!LC 6AA[csxxz[A&C!23u:w3:A:;"=CJ  t 455%6s5z77>>?&AE
 ' $F5h-H}"3D .6 .%,.		sJ'J	3DxC7C	SdEWE		 $T( ,#*,		s6 =(0=4;=	CT ' '%'		s 9H&,9079		sk *!(*	ct&)I4<I@GI		*3Dt+1I4<I@GI 
	s4 =(0=4;=		!#4d @+3@7>@		$Sd C.6C:AC		)#4d H3;H?FH ?6(344ceeWg6"&&9CLx)511
:JM Bs   [c                    [        U[        5      (       d  U4n[        U5      (       a  SnOUc  Uc  SOSnOUR                  5       nUc  0 nUb  US;   a  SU S3n[	        U5      eUbV  [        U5      nUS:X  a  SU;  a  [        S[        S	S
9  XVS'   O+US:X  a  UR                  SU5        OUR                  SU5        UR                  S5      n	[        U	[        5      (       a  S	[        U	5      -  US'   US:X  a  U" U 4X1US.UD6n
ObUS:X  a  [        [        XU40 UD6n
OIUS:X  a  Uc  [	        S5      e[        XU40 UD6n
O'US:X  a  [        [        XU40 UD6n
O[	        SU 35      e[         R"                  " U
R$                  5      S   U
l        [         R&                  " U
R(                  U
R$                  R*                  5      S   U
l        U
$ )a$  Local minimization of scalar function of one variable.

Parameters
----------
fun : callable
    Objective function.
    Scalar function, must return 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.

bracket : sequence, optional
    For methods 'brent' and 'golden', `bracket` defines the bracketing
    interval and is required.
    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 ``res.x`` will not necessarily satisfy
    ``xa <= res.x <= xb``.
bounds : sequence, optional
    For method 'bounded', `bounds` is mandatory and must have two finite
    items corresponding to the optimization bounds.
args : tuple, optional
    Extra arguments passed to the objective function.
method : str or callable, optional
    Type of solver.  Should be one of:

    - :ref:`Brent <optimize.minimize_scalar-brent>`
    - :ref:`Bounded <optimize.minimize_scalar-bounded>`
    - :ref:`Golden <optimize.minimize_scalar-golden>`
    - custom - a callable object (added in version 0.14.0), see below

    Default is "Bounded" if bounds are provided and "Brent" otherwise.
    See the 'Notes' section for details of each solver.

tol : float, optional
    Tolerance for termination. For detailed control, use solver-specific
    options.
options : dict, optional
    A dictionary of solver options.

    maxiter : int
        Maximum number of iterations to perform.
    disp : bool
        Set to True to print convergence messages.

    See :func:`show_options()` for solver-specific options.

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.

See also
--------
minimize : Interface to minimization algorithms for scalar multivariate
    functions
show_options : Additional options accepted by the solvers

Notes
-----
This section describes the available solvers that can be selected by the
'method' parameter. The default method is the ``"Bounded"`` Brent method if
`bounds` are passed and unbounded ``"Brent"`` otherwise.

Method :ref:`Brent <optimize.minimize_scalar-brent>` uses Brent's
algorithm [1]_ to find a local minimum.  The algorithm uses inverse
parabolic interpolation when possible to speed up convergence of
the golden section method.

Method :ref:`Golden <optimize.minimize_scalar-golden>` uses the
golden section search technique [1]_. It uses analog of the bisection
method to decrease the bracketed interval. It is usually
preferable to use the *Brent* method.

Method :ref:`Bounded <optimize.minimize_scalar-bounded>` can
perform bounded minimization [2]_ [3]_. It uses the Brent method to find a
local minimum in the interval x1 < xopt < x2.

Note that the Brent and Golden methods do not guarantee success unless a
valid ``bracket`` triple is provided. If a three-point bracket cannot be
found, consider `scipy.optimize.minimize`. Also, all methods are intended
only for local minimization. When the function of interest has more than
one local minimum, consider :ref:`global_optimization`.

**Custom minimizers**

It may be useful to pass a custom minimization method, for example
when using some library frontend to minimize_scalar. You can simply
pass a callable as the ``method`` parameter.

The callable is called as ``method(fun, args, **kwargs, **options)``
where ``kwargs`` corresponds to any other parameters passed to `minimize`
(such as `bracket`, `tol`, etc.), except the `options` dict, which has
its contents also passed as `method` parameters pair by pair.  The method
shall return an `OptimizeResult` object.

The provided `method` callable must be able to accept (and possibly ignore)
arbitrary parameters; the set of parameters accepted by `minimize` may
expand in future versions and then these parameters will be passed to
the method. You can find an example in the scipy.optimize tutorial.

.. versionadded:: 0.11.0

References
----------
.. [1] Press, W., S.A. Teukolsky, W.T. Vetterling, and B.P. Flannery.
       Numerical Recipes in C. Cambridge University Press.
.. [2] Forsythe, G.E., M. A. Malcolm, and C. B. Moler. "Computer Methods
       for Mathematical Computations." Prentice-Hall Series in Automatic
       Computation 259 (1977).
.. [3] Brent, Richard P. Algorithms for Minimization Without Derivatives.
       Courier Corporation, 2013.

Examples
--------
Consider the problem of minimizing the following function.

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

Using the *Brent* method, we find the local minimum as:

>>> from scipy.optimize import minimize_scalar
>>> res = minimize_scalar(f)
>>> res.fun
-9.9149495908

The minimizer is:

>>> res.x
1.28077640403

Using the *Bounded* method, we find a local minimum with specified
bounds as:

>>> res = minimize_scalar(f, bounds=(-3, -1), method='bounded')
>>> res.fun  # minimum
3.28365179850e-13
>>> res.x  # minimizer
-2.0000002026

r>   r5   r6   >   r5   r7   z-Use of `bounds` is incompatible with 'method=z'.rC   z\Method 'bounded' does not support relative tolerance in x; defaulting to absolute tolerance.r?   r@   rH   rE   disp)rK   bracketrO   z9The `bounds` parameter is mandatory for method `bounded`.r7   rV    )rb   rc   rd   re   r^   rk   r   rg   rl   ri   rf   intr   r   r   r   rZ   r\   rT   reshaperx   shape)rT   r   rO   rK   r   rH   r   r   r}   r   r   s              r   r   r     s   t dE""w	 .wi||~d&99A&L!!
w-9!7 5A/  #GYuc*vs+ ;;vD$c$i-ySOtVOwO	)*@*-I@GI		> 1 2 2&sDDGD		)*A*-I@GI ?6(344
 jj!"%CGJJsuucggmm,R0CEJ    c                 X    U R                   U)    nU R                  U)    n[        X#5      $ )z0Removes fixed variables from a `Bounds` instance)rp   rq   r#   )rO   r   rp   rq   s       r   rt   rt     s,    	G8	B	G8	B">r   c                 $   ^ ^^^^ U UUUU4S jnU$ )z@Wraps a function such that fixed variables need not be passed inc                 N  > [         R                  " TU R                  S9nT	UT'   XT) '   T" U/UQ70 UD6n[         R                  " U5      nTS:X  a  [         R                  " U5      nOTS:X  a  [         R
                  " U5      nTS:X  a
  UST) 4   nU$ TS:X  a	  UT) T) 4   nU$ )Nr:   r   r?   .)rZ   
zeros_liker;   arrayr[   
atleast_2d)
x_inrK   kwargsx_outy_outfun_inr   rU   rS   r   s
        r   fun_out"_remove_from_func.<locals>.fun_out  s    gTZZ8 gwhu.t.v.a<MM%(E\MM%(EQ;#x-(E  q[7(WH,-Er   r   )r   r   r   rU   rS   r   s   ````` r   ru   ru     s     $ Nr   c                     U) nU R                   S:X  a  USS2S4   USSS24   -  n[        R                  " X0R                  S9nX$U) '   U R	                  5       XC'   U$ )z%Adds fixed variables back to an arrayr?   Nr:   )r]   rZ   r   r;   ravel)r   r   r   i_freer   s        r   rw   rw     s[    XFyyA~46$'?2MM&

3E6'NJJLEMLr   c                    Sn[         R                  " U R                  U R                  :  5      (       a  [	        U5      eSn [         R
                  " U R                  UR                  5      U l        [         R
                  " U R                  UR                  5      U l        U $ ! [         a  n[	        U5      UeSnAff = f)zCheck that bounds are valid.z:An upper bound is less than the corresponding lower bound.z?The number of bounds is not compatible with the length of `x0`.N)rZ   rh   rq   rp   r^   broadcast_tor   	Exception)rO   r~   r   msges        r   ro   ro     s     GC	vvfii&))#$$o
KC%OOFIIrxx8	OOFIIrxx8	 M  %o1$%s   A B% %
C /B;;C c                    US;   a/  [        U [        5      (       d  [        U 5      u  p4[        X45      n U $ US;   aC  [        U [        5      (       a.  [        U R                  U R
                  UR                  S   5      n U $ )z3Converts bounds to the form required by the solver.>   rR   r-   r.   r'   r&   r0   )r+   r,   r/   oldr   )rb   r#   r   r   rp   rq   r   )rO   r~   r   rp   rq   s        r   rn   rn     ss      &&))%f-FBB^F M 
4	4ff%%&vyy&))RXXa[IFMr   c                    [         [        [        4nUSS nU c  / n O[        X5      (       a  U /n O[	        U 5      n US;   a5  [        U 5       H$  u  pV[        Xd5      (       a  M  [        XV5      X'   M&     U $ [        [	        U 5      5       H=  u  pV[        Xd5      (       d  M  [        Xa5      nUS   X'   U R                  USS 5        M?     U $ )z8Converts constraints to the form required by the solver.N)r0   r.   rR   r   r   )	r!   r"   rk   rb   list	enumerater   r    extend)rP   r~   r   all_constraint_typesnew_constraint_typesir   old_constraintss           r   rm   rm   *  s    /1A4H/4	K	6	6"m;'00,FAc88!6q!> -   [ 12FA#44"7"@!0!3""?12#67	 3 r   c           
      L   SnSnUR                   nU(       a  Sn[        XGS5      nSnU Hd  n	[        X5      n
U
R                  U5      n[        R
                  " U5      (       d  M<  [        U[        R                  " U5      5      nSnSU S3nMf     [        Xp" U/UQ76 XVS	SSS
9$ )z
Provides a default OptimizeResult for when a bounded minimization method
has (lb == ub).all().

Parameters
----------
fun: callable
bounds: Bounds
method: str
constraints: Constraint
Tz/All independent variables were fixed by bounds.zVAll independent variables were fixed by bounds at values that satisfy the constraints.rR   r   FzAll independent variables were fixed by bounds, but the independent variables do not satisfy the constraints exactly. (Maximum violation: z).r   )rx   rT   r{   r}   nfevnjevnhev)rp   rm   r$   	violationrZ   summaxr   )rT   rO   r   rK   rP   r{   r}   r~   maxcvcpcr   s               r   rs   rs   D  s     G?G 
B4-kuEE&LL$	66)rvvi01EGCCH'MG  
#b.4.'Q r   )
r   NNNNNr   NNN)NNr   NNN)Nr   )r   r   )>__doc____all__warningsr   numpyrZ   	_optimizer   r   r	   r
   r   r   r   r   r   r   r   r   _trustregion_doglegr   _trustregion_ncgr   _trustregion_krylovr   _trustregion_exactr   _trustregion_constrr   
_lbfgsb_pyr   _tncr   
_cobyla_pyr   
_cobyqa_pyr   	_slsqp_pyr   _constraintsr   r   r   r    r!   r"   r#   r$   _differentiable_functionsr%   MINIMIZE_METHODSMINIMIZE_METHODS_NEW_CBMINIMIZE_SCALAR_METHODSr   r   rt   ru   rw   ro   rn   rm   rs   r   r   r   <module>r      s    (
)  E E E E
 2 1 7 ; = )  ( ( &/ / / 2$ D  9 ;?:>$(Yx :<37Pf. 
6 35'r   