
    ^Mh7R                     T   d Z ddlZddlmZmZmZmZ ddlmZ ddl	m
Z
mZmZmZmZmZ ddlmZ ddlmZ d	d
gZdddddddddd	Zi ddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>
Z	 	 	 	 	 	 dKdGZ	 	 	 	 	 dLdIZ G dJ d
e          ZdS )MzR
Functions
---------
.. autosummary::
   :toctree: generated/

    fmin_l_bfgs_b

    N)arrayasarrayfloat64zeros   )_lbfgsb)
MemoizeJacOptimizeResult_call_callback_maybe_halt_wrap_callback_check_unknown_options_prepare_scalar_function)old_bound_to_new)LinearOperatorfmin_l_bfgs_bLbfgsInvHessProductSTARTNEW_XRESTARTFGCONVERGENCESTOPWARNINGERRORABNORMAL)	r   r                         i-  i.  i  z#NORM OF PROJECTED GRADIENT <= PGTOLi  z'RELATIVE REDUCTION OF F <= FACTR*EPSMCHi  zCPU EXCEEDING THE TIME LIMIT  z*TOTAL NO. OF F,G EVALUATIONS EXCEEDS LIMITi  z(PROJECTED GRADIENT IS SUFFICIENTLY SMALL  z%TOTAL NO. OF ITERATIONS REACHED LIMIT  zCALLBACK REQUESTED HALTiY  z ROUNDING ERRORS PREVENT PROGRESSiZ  zSTP = STPMAXi[  zSTP = STPMINi\  zXTOL TEST SATISFIEDi  zNO FEASIBLE SOLUTIONi  z	FACTR < 0i  zFTOL < 0zGTOL < 0zXTOL < 0zSTP < STPMINzSTP > STPMAXz
STPMIN < 0zSTPMAX < STPMINzINITIAL G >= 0zM <= 0zN <= 0zINVALID NBD)
i  i  i  i  i  i  i  i  i  i   
       cAh㈵>:0yE>:     c           	      V   |r| }d}n|t          |           }|j        }n| }|}t          |          }||t          j        t
                    j        z  ||	||||d}t          ||f|||d|}|d         |d         |d         |d         |d         d	}|d
         }|d         }|||fS )a%  
    Minimize a function func using the L-BFGS-B algorithm.

    Parameters
    ----------
    func : callable f(x,*args)
        Function to minimize.
    x0 : ndarray
        Initial guess.
    fprime : callable fprime(x,*args), optional
        The gradient of `func`. If None, then `func` returns the function
        value and the gradient (``f, g = func(x, *args)``), unless
        `approx_grad` is True in which case `func` returns only ``f``.
    args : sequence, optional
        Arguments to pass to `func` and `fprime`.
    approx_grad : bool, optional
        Whether to approximate the gradient numerically (in which case
        `func` returns only the function value).
    bounds : list, optional
        ``(min, max)`` pairs for each element in ``x``, defining
        the bounds on that parameter. Use None or +-inf for one of ``min`` or
        ``max`` when there is no bound in that direction.
    m : int, optional
        The maximum number of variable metric corrections
        used to define the limited memory matrix. (The limited memory BFGS
        method does not store the full hessian but uses this many terms in an
        approximation to it.)
    factr : float, optional
        The iteration stops when
        ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``,
        where ``eps`` is the machine precision, which is automatically
        generated by the code. Typical values for `factr` are: 1e12 for
        low accuracy; 1e7 for moderate accuracy; 10.0 for extremely
        high accuracy. See Notes for relationship to `ftol`, which is exposed
        (instead of `factr`) by the `scipy.optimize.minimize` interface to
        L-BFGS-B.
    pgtol : float, optional
        The iteration will stop when
        ``max{|proj g_i | i = 1, ..., n} <= pgtol``
        where ``proj g_i`` is the i-th component of the projected gradient.
    epsilon : float, optional
        Step size used when `approx_grad` is True, for numerically
        calculating the gradient
    iprint : int, optional
        Deprecated option that previously controlled the text printed on the
        screen during the problem solution. Now the code does not emit any
        output and this keyword has no function.

        .. deprecated:: 1.15.0
            This keyword is deprecated and will be removed from SciPy 1.17.0.

    disp : int, optional
        Deprecated option that previously controlled the text printed on the
        screen during the problem solution. Now the code does not emit any
        output and this keyword has no function.

        .. deprecated:: 1.15.0
            This keyword is deprecated and will be removed from SciPy 1.17.0.

    maxfun : int, optional
        Maximum number of function evaluations. Note that this function
        may violate the limit because of evaluating gradients by numerical
        differentiation.
    maxiter : int, optional
        Maximum number of iterations.
    callback : callable, optional
        Called after each iteration, as ``callback(xk)``, where ``xk`` is the
        current parameter vector.
    maxls : int, optional
        Maximum number of line search steps (per iteration). Default is 20.

    Returns
    -------
    x : array_like
        Estimated position of the minimum.
    f : float
        Value of `func` at the minimum.
    d : dict
        Information dictionary.

        * d['warnflag'] is

          - 0 if converged,
          - 1 if too many function evaluations or too many iterations,
          - 2 if stopped for another reason, given in d['task']

        * d['grad'] is the gradient at the minimum (should be 0 ish)
        * d['funcalls'] is the number of function calls made.
        * d['nit'] is the number of iterations.

    See also
    --------
    minimize: Interface to minimization algorithms for multivariate
        functions. See the 'L-BFGS-B' `method` in particular. Note that the
        `ftol` option is made available via that interface, while `factr` is
        provided via this interface, where `factr` is the factor multiplying
        the default machine floating-point precision to arrive at `ftol`:
        ``ftol = factr * numpy.finfo(float).eps``.

    Notes
    -----
    SciPy uses a C-translated and modified version of the Fortran code,
    L-BFGS-B v3.0 (released April 25, 2011, BSD-3 licensed). Original Fortran
    version was written by Ciyou Zhu, Richard Byrd, Jorge Nocedal and,
    Jose Luis Morales.

    References
    ----------
    * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
      Constrained Optimization, (1995), SIAM Journal on Scientific and
      Statistical Computing, 16, 5, pp. 1190-1208.
    * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
      FORTRAN routines for large scale bound constrained optimization (1997),
      ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.
    * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B,
      FORTRAN routines for large scale bound constrained optimization (2011),
      ACM Transactions on Mathematical Software, 38, 1.

    Examples
    --------
    Solve a linear regression problem via `fmin_l_bfgs_b`. To do this, first we
    define an objective function ``f(m, b) = (y - y_model)**2``, where `y`
    describes the observations and `y_model` the prediction of the linear model
    as ``y_model = m*x + b``. The bounds for the parameters, ``m`` and ``b``,
    are arbitrarily chosen as ``(0,5)`` and ``(5,10)`` for this example.

    >>> import numpy as np
    >>> from scipy.optimize import fmin_l_bfgs_b
    >>> X = np.arange(0, 10, 1)
    >>> M = 2
    >>> B = 3
    >>> Y = M * X + B
    >>> def func(parameters, *args):
    ...     x = args[0]
    ...     y = args[1]
    ...     m, b = parameters
    ...     y_model = m*x + b
    ...     error = sum(np.power((y - y_model), 2))
    ...     return error

    >>> initial_values = np.array([0.0, 1.0])

    >>> x_opt, f_opt, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y),
    ...                                    approx_grad=True)
    >>> x_opt, f_opt
    array([1.99999999, 3.00000006]), 1.7746231151323805e-14  # may vary

    The optimized parameters in ``x_opt`` agree with the ground truth parameters
    ``m`` and ``b``. Next, let us perform a bound constrained optimization using
    the `bounds` parameter.

    >>> bounds = [(0, 5), (5, 10)]
    >>> x_opt, f_op, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y),
    ...                                   approx_grad=True, bounds=bounds)
    >>> x_opt, f_opt
    array([1.65990508, 5.31649385]), 15.721334516453945  # may vary
    N)maxcorftolgtolepsmaxfunmaxitercallbackmaxls)argsjacboundsr9   messagenfevnitstatus)gradtaskfuncallsr=   warnflagfunx)r	   
derivativer   npfinfofloatr3   _minimize_lbfgsb)funcx0fprimer8   approx_gradr:   mfactrpgtolepsiloniprintr4   r5   dispr6   r7   rC   r9   optsresdfrD   s                          Y/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_lbfgsb_py.pyr   r   \   s    H  	n h''HBHUOO//  D 3 #3v # #!# #CUY[E
]		$ 	$A
 	E
ACAa7N        #>c                 	   t          |           |}|}|t          j        t                    j        z  }t          |                                          }|j        \  }|nt          |          |k    rt          d          t          j
        t          |                    }|d         |d         k                                    rt          d          t          j        ||d         |d                   }t          | ||||	||          }|j        }t!          |t          j                  }t!          |t$                    }t!          |t$                    }t          j         t          j        fddt          j        fdddt          j         dfd	i}|jt)          d|          D ]Y}|d|f         |d|f         }}t          j        |          s|||<   d}t          j        |          s|||<   d}|||f         ||<   Z|dk    st          d
          t          |t          j                  }t          dt          j                  }t!          |ft          j                  } t!          d|z  |z  d|z  z   d|z  |z  z   d|z  z   t$                    }!t!          d	|z  t          j                  }"t!          dt          j                  }#t!          dt          j                  }$t!          dt          j                  }%t!          dt          j                  }&t!          dt$                    }'d}(	 |                     t          j                  } t/          j        ||||||| |||!|"|#|%|&|'||$           |#d         d	k    r ||          \  }} nd|#d         dk    rW|(dz  }(t3          ||          })t5          ||)          r
d|#d<   d|#d<   |(|k    rd|#d<   d|#d<   n|j        |
k    r
d|#d<   d|#d<   nn|#d         dk    rd}*n|j        |
k    s|(|k    rd}*nd}*|!d||z                               ||          }+|!||z  d|z  |z                               ||          },|&d         }-t;          |-|          }.t=          |+d|.         |,d|.                   }/t>          |#d                  dz   t@          |#d                  z   }0t3          || |j        |j!        |(|*|0||*dk    |/
  
        S )aa
  
    Minimize a scalar function of one or more variables using the L-BFGS-B
    algorithm.

    Options
    -------
    disp : None or int
        Deprecated option that previously controlled the text printed on the
        screen during the problem solution. Now the code does not emit any
        output and this keyword has no function.

        .. deprecated:: 1.15.0
            This keyword is deprecated and will be removed from SciPy 1.17.0.

    maxcor : int
        The maximum number of variable metric corrections used to
        define the limited memory matrix. (The limited memory BFGS
        method does not store the full hessian but uses this many terms
        in an approximation to it.)
    ftol : float
        The iteration stops when ``(f^k -
        f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol``.
    gtol : float
        The iteration will stop when ``max{|proj g_i | i = 1, ..., n}
        <= gtol`` where ``proj g_i`` is the i-th component of the
        projected gradient.
    eps : float or ndarray
        If `jac is None` the absolute step size used for numerical
        approximation of the jacobian via forward differences.
    maxfun : int
        Maximum number of function evaluations. Note that this function
        may violate the limit because of evaluating gradients by numerical
        differentiation.
    maxiter : int
        Maximum number of iterations.
    iprint : int, optional
        Deprecated option that previously controlled the text printed on the
        screen during the problem solution. Now the code does not emit any
        output and this keyword has no function.

        .. deprecated:: 1.15.0
            This keyword is deprecated and will be removed from SciPy 1.17.0.

    maxls : int, optional
        Maximum number of line search steps (per iteration). Default is 20.
    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 ``method='3-point'``
        the sign of `h` is ignored. If None (default) then step is selected
        automatically.

    Notes
    -----
    The option `ftol` is exposed via the `scipy.optimize.minimize` interface,
    but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The
    relationship between the two is ``ftol = factr * numpy.finfo(float).eps``.
    I.e., `factr` multiplies the default machine floating-point precision to
    arrive at `ftol`.

    Nz length of x0 != length of boundsr   r   z@LBFGSB - one of the lower bounds is greater than an upper bound.)r9   r8   rQ   r:   finite_diff_rel_step)r   r   r   r   zmaxls must be positive.)dtypeg        r      r"   r   ,      T)rD   rC   r&   r%   r$      z: )
rC   r9   r<   njevr=   r>   r;   rD   successhess_inv)"r   rF   rG   rH   r3   r   ravelshapelen
ValueErrorr   r   anyclipr   fun_and_gradr   int32r   infrangeisinfastyper   setulbr
   r   r<   reshapeminr   status_messagestask_messagesngev)1rC   rK   r8   r9   r:   rS   r0   r1   r2   r3   r4   r5   rR   r6   r7   r\   unknown_optionsrN   rP   rO   nsffunc_and_gradnbdlow_bnd	upper_bnd
bounds_mapiLUrD   rW   gwaiwar@   ln_tasklsaveisavedsaven_iterationsintermediate_resultrB   syn_bfgs_updatesn_corrsrd   msgs1                                                    rX   rI   rI   "  s:   F ?+++AE28E??&&E					B	BA
 ~	V		;<<<*62233 1Iq	!&&(( 	R   WRF1I.. 
"#rss)/7K
M 
M 
MB OM
28

CAwGa!!IF7BF#Qbf+q!F7A,#J
 q! 	& 	&A!Q$<1qA8A;; 
8A;;  	!1%CFF1992333b
###Ac"""Aqd"(###A	qs1uqs{RT!V#ac)7	3	3B
!28
$
$
$C"(###DARX&&&G!28$$$E"BH%%%E"G$$$EL HHRZ  q!WiaE5"D%ug	G 	G 	G 7a<<
 !=##DAqq!W\\AL"01!"<"<"<(3FGG QQw&&QQ6!!QQ=@ Aw!||	6		\W44 	1ac6
1a  A
1Q3!A:q!$$A 2YN.&))G"1XgX;(7(<<H
$q'
"T
)M$q',B
BCaQRW!w*8SAK K K KrY   c                   .     e Zd ZdZ fdZd Zd Z xZS )r   aM  Linear operator for the L-BFGS approximate inverse Hessian.

    This operator computes the product of a vector with the approximate inverse
    of the Hessian of the objective function, using the L-BFGS limited
    memory approximation to the inverse Hessian, accumulated during the
    optimization.

    Objects of this class implement the ``scipy.sparse.linalg.LinearOperator``
    interface.

    Parameters
    ----------
    sk : array_like, shape=(n_corr, n)
        Array of `n_corr` most recent updates to the solution vector.
        (See [1]).
    yk : array_like, shape=(n_corr, n)
        Array of `n_corr` most recent updates to the gradient. (See [1]).

    References
    ----------
    .. [1] Nocedal, Jorge. "Updating quasi-Newton matrices with limited
       storage." Mathematics of computation 35.151 (1980): 773-782.

    c                 4   |j         |j         k    s|j        dk    rt          d          |j         \  }}t                                          t
          j        ||f           || _        || _        || _	        dt          j
        d||          z  | _        dS )zConstruct the operator.r   z0sk and yk must have matching shape, (n_corrs, n))r]   rf   r   zij,ij->iN)rf   ndimrh   super__init__rF   r   skykr   einsumrho)selfr   r   r   rx   	__class__s        rX   r   zLbfgsInvHessProduct.__init__  s    8rx27a<<OPPPX
rz!Q888ryR444rY   c                 H   | j         | j        | j        | j        f\  }}}}t	          j        || j        d          }|j        dk    r&|j        d         dk    r|	                    d          }t	          j
        |          }t          |dz
  dd          D ]=}||         t	          j        ||         |          z  ||<   |||         ||         z  z
  }>|}	t          |          D ]=}||         t	          j        ||         |	          z  }
|	||         ||         |
z
  z  z   }	>|	S )aE  Efficient matrix-vector multiply with the BFGS matrices.

        This calculation is described in Section (4) of [1].

        Parameters
        ----------
        x : ndarray
            An array with shape (n,) or (n,1).

        Returns
        -------
        y : ndarray
            The matrix-vector product

        T)r]   copyr   r   r,   )r   r   r   r   rF   r   r]   r   rf   rr   emptyrn   dot)r   rD   r   r   r   r   qalphar   rbetas              rX   _matveczLbfgsInvHessProduct._matvec  s!     "Wdgt|TXE1gsHQdjt4446Q;;171:??		"A!!wqy"b)) 	" 	"A1vqtQ/E!HE!HQqTM!AAw 	- 	-Aq6BF1Q4OO+DAaDE!HtO,,AArY   c                    | j         | j        | j        | j        f\  }}}}t	          j        | j        d| j        i}|}t          |          D ]}|||         ddt          j	        f         ||         t          j	        ddf         z  ||         z  z
  }|||         ddt          j	        f         ||         t          j	        ddf         z  ||         z  z
  }	t	          j
        |t	          j
        ||	                    ||         ||         ddt          j	        f         z  ||         t          j	        ddf         z  z   }|S )zReturn a dense array representation of this operator.

        Returns
        -------
        arr : ndarray, shape=(n, n)
            An array with the same shape and containing
            the same data represented by this `LinearOperator`.

        r]   N)r   r   r   r   rF   eyerf   r]   rn   newaxisr   )
r   r   r   r   r   I_arrHkr   A1A2s
             rX   todensezLbfgsInvHessProduct.todense.  s5    "Wdgt|TXE1gs
5$*55w 	M 	MA1aaam,qtBJM/BBSVKKB1aaam,qtBJM/BBSVKKBBF2rNN++s1v!QQQ
]8K/K89!RZ]8K0L MBB	rY   )__name__
__module____qualname____doc__r   r   r   __classcell__)r   s   @rX   r   r     sa         25 5 5 5 5     D      rY   )Nr'   r   Nr(   r)   r*   r+   r,   r-   r-   NNr.   )r'   NNNr(   rZ   r*   r+   r-   r-   r,   Nr.   N)r   numpyrF   r   r   r   r   r#   r   	_optimizer	   r
   r   r   r   r   _constraintsr   scipy.sparse.linalgr   __all__rt   ru   r   rI   r   r'   rY   rX   <module>r      s   F     0 0 0 0 0 0 0 0 0 0 0 0      2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 + * * * * * . . . . . .1
2 	
 
" " 
/	
 
3 
( 
6 
4 
1 
# 
, . . 
 
   +!" *#$ 








7  < /16:?C')C C C CL 9=0F@E57*.	@K @K @K @KF] ] ] ] ]. ] ] ] ] ]rY   