
    (ph7R                     P   S r SSKrSSKJrJrJrJr  SSKJr  SSK	J
r
JrJrJrJrJr  SSKJr  SSKJr  S	S
/rSSSSSSSSSS.	r0 SS_SS_SS_SS_SS_SS_SS_S S!_S"S#_S$S%_S&S'_S(S)_S*S+_S,S-_S.S/_S0S1_S2S3_S4S5S6S7S8S9S:S;S<S=S>.
Er      SBS? jr     SCS@ jr " SA S
\5      rg)DzR
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  c           	      <   U(       a  U nSnOUc  [        U 5      nUR                  nOU nUn[        U5      nUU[        R                  " [
        5      R                  -  UU	UUUUS.n[        UU4UUUS.UD6nUS   US   US   US   US   S	.nUS
   nUS   nUUU4$ )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boundsr1   messagenfevnitstatus)gradtaskfuncallsr5   warnflagfunx)r	   
derivativer   npfinfofloatr+   _minimize_lbfgsb)funcx0fprimer0   approx_gradr2   mfactrpgtolepsiloniprintr,   r-   dispr.   r/   r;   r1   optsresdfr<   s                          L/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_lbfgsb_py.pyr   r   \   s    H 	nn h'HBHHUO/// D 3 #3v #!#CUY[E
]		$A
 	E
ACAa7N    c                 	   [        U5        UnUnU[        R                  " [        5      R                  -  n[        U5      R                  5       nUR                  u  nUc  O[        U5      U:w  a  [        S5      e[        R                  " [        U5      5      nUS   US   :  R                  5       (       a  [        S5      e[        R                  " XS   US   5      n[        XX2U	UUS9nUR                  n[!        U[        R"                  5      n[!        U[$        5      n[!        U[$        5      n[        R&                  * [        R&                  4SS[        R&                  4SSS[        R&                  * S4S	0nUbo  [)        SU5       H_  nUSU4   USU4   nn[        R*                  " U5      (       d  UUU'   Sn[        R*                  " U5      (       d  UUU'   SnUUU4   UU'   Ma     US:  d  [        S
5      e[        U[        R$                  S9n[        S[        R"                  S9n[!        U4[        R"                  S9n [!        SU-  U-  SU-  -   SU-  U-  -   SU-  -   [$        5      n![!        S	U-  [        R"                  S9n"[!        S[        R"                  S9n#[!        S[        R"                  S9n$[!        S[        R"                  S9n%[!        S[        R"                  S9n&[!        S[$        S9n'Sn( U R-                  [        R$                  5      n [.        R0                  " UUUUUUU UUU!U"U#U%U&U'UU$5        U#S   S	:X  a  U" U5      u  nn O`U#S   S:X  aV  U(S-  n([3        UUS9n)[5        UU)5      (       a
  SU#S'   SU#S'   U(U:  a  SU#S'   SU#S'   OUR6                  U
:  a
  SU#S'   SU#S'   OOM  U#S   S:X  a  Sn*OUR6                  U
:  d  U(U:  a  Sn*OSn*U!SUU-   R9                  UU5      n+U!UU-  SU-  U-   R9                  UU5      n,U&S   n-[;        U-U5      n.[=        U+SU. U,SU. 5      n/[>        U#S      S-   [@        U#S      -   n0[3        UU UR6                  URB                  U(U*U0UU*S:H  U/S9
$ )a	  
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.)r1   r0   rI   r2   finite_diff_rel_step)r   r   r   r   zmaxls must be positive.)dtypeg        r      r"   r   ,      )r<   r;   r&   r%   r$      z: )
r;   r1   r4   njevr5   r6   r3   r<   successhess_inv)"r   r>   r?   r@   r+   r   ravelshapelen
ValueErrorr   r   anyclipr   fun_and_gradr   int32r   infrangeisinfastyper   setulbr
   r   r4   reshapeminr   status_messagestask_messagesngev)1r;   rC   r0   r1   r2   rK   r(   r)   r*   r+   r,   r-   rJ   r.   r/   rS   unknown_optionsrF   rH   rG   nsffunc_and_gradnbdlow_bnd	upper_bnd
bounds_mapiLUr<   rO   gwaiwar8   ln_tasklsaveisavedsaven_iterationsintermediate_resultr:   syn_bfgs_updatesn_corrsr[   msgs1                                                    rP   rA   rA   "  s   F ?+AE288E?&&&E				B	BA
 ~	V	;<<*623 1Iq	!&&((R  WWRF1I. 
"#ss)/7K
MB OOM
288
CAwGa!IFF7BFF#Qbff+q!FF7A,#J
 q!A!Q$<1qA88A;;
88A;; 	!1%CF  19233b

#Ac"Aqd"((#A	qs1uqs{RT!V#ac)7	3B
!288
$C"((#DARXX&G!288$E"BHH%E"G$EL
 HHRZZ q!WiaE5"D%ug	G 7a<
 !#DAq!W\AL"01!"<(3FGGQQw&QQ6!QQ= @ Aw!|	6	\W4 	1ac
1a A
1Q3!Aq!$A 2YN.&)G"1Xg;(7<H
$q'
"T
)M$q',B
BCaQRWW!ww*8SAK KrQ   c                   8   ^  \ rS rSrSrU 4S jrS rS rSrU =r	$ )r   i  a  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                 (  > UR                   UR                   :w  d  UR                  S:w  a  [        S5      eUR                   u  p4[        TU ]  [
        R                  XD4S9  Xl        X l        X0l	        S[
        R                  " SX5      -  U l        g)zConstruct the operator.r   z0sk and yk must have matching shape, (n_corrs, n))rT   r]   r   zij,ij->iN)r]   ndimr_   super__init__r>   r   skykr   einsumrho)selfr   r   r   ro   	__class__s        rP   r   LbfgsInvHessProduct.__init__  sr    88rxx277a<OPPXX
rzz!8ryyR44rQ   c                 B   U R                   U R                  U R                  U R                  4u  p#pE[        R
                  " XR                  SS9nUR                  S:X  a$  UR                  S   S:X  a  UR                  S5      n[        R                  " U5      n[        US-
  SS5       H/  nXX   [        R                  " X(   U5      -  Xx'   XgU   X8   -  -
  nM1     Un	[        U5       H0  nXX   [        R                  " X8   U	5      -  n
XU   Xx   U
-
  -  -   n	M2     U	$ )zEfficient 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)rT   copyr   r   )r   r   r   r   r>   r   rT   r   r]   ri   emptyre   dot)r   r<   r   r   r   r   qalpharv   rbetas              rP   _matvecLbfgsInvHessProduct._matvec  s      "WWdggt||TXXEgHHQjjt466Q;1771:?		"A!wqy"b)AvqtQ/EH!HQTM!A * wA6BFF14O+DaDEHtO,,A   rQ   c                    U R                   U R                  U R                  U R                  4u  pp4[        R
                  " U R                  SU R                  06nUn[        U5       H  nXQU   SS2[        R                  4   X'   [        R                  SS24   -  XG   -  -
  nXRU   SS2[        R                  4   X   [        R                  SS24   -  XG   -  -
  n	[        R                  " U[        R                  " Xi5      5      XG   X   SS2[        R                  4   -  X   [        R                  SS24   -  -   nM     U$ )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`.

rT   N)r   r   r   r   r>   eyer]   rT   re   newaxisr   )
r   r   r   r   r   I_arrHkrv   A1A2s
             rP   todenseLbfgsInvHessProduct.todense.  s    "WWdggt||TXXEg

5$**5wA1am,qtBJJM/BBSVKKB1am,qtBJJM/BBSVKKBBFF2N+svQ

]8K/K89RZZ]8K0L MB	   	rQ   )r   r   r   r   )
__name__
__module____qualname____firstlineno____doc__r   r   r   __static_attributes____classcell__)r   s   @rP   r   r     s    25 D rQ   )N r   N
   g    cAh㈵>:0yE>r   :  r   NN   )r   NNNr   g    #>r   r   r   r   r   Nr   N)r   numpyr>   r   r   r   r   r#   r   	_optimizer	   r
   r   r   r   r   _constraintsr   scipy.sparse.linalgr   __all__rk   rl   r   rA   r   r   rQ   rP   <module>r      s  F  0 0 2 2 + .1
2 	
" " 
/	
 
3 
( 
6 
4 
1 
# 
, . . 
 
   +!" *#$ 








7< /16:?C')CL 9=0F@E57*.	@KF]. ]rQ   