L i5ZdZddlZddlmZmZmZmZddlmZddl m Z m Z m Z m Z mZmZddlmZddlmZdd lmZddlZd d gZd d dddddddd Zidddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd? Zdd@dddAdBdCdDedEdEeddFfdGZd@ddedAdHdCdDdEdEeddFddfdIZGdJd eZy)KzR Functions --------- .. autosummary:: :toctree: generated/ fmin_l_bfgs_b N)arrayasarrayfloat64zeros)_lbfgsb) MemoizeJacOptimizeResult_call_callback_maybe_halt_wrap_callback_check_unknown_options_prepare_scalar_function)old_bound_to_new)LinearOperator)_NoValue fmin_l_bfgs_bLbfgsInvHessProductSTARTNEW_XRESTARTFG CONVERGENCESTOPWARNINGERRORABNORMAL) rri-i.iz#NORM OF PROJECTED GRADIENT <= PGTOLiz'RELATIVE REDUCTION OF F <= FACTR*EPSMCHizCPU EXCEEDING THE TIME LIMITz*TOTAL NO. OF F,G EVALUATIONS EXCEEDS LIMITiz(PROJECTED GRADIENT IS SUFFICIENTLY SMALLz%TOTAL NO. OF ITERATIONS REACHED LIMITzCALLBACK REQUESTED HALTiYz ROUNDING ERRORS PREVENT PROGRESSiZz STP = STPMAXi[z STP = STPMINi\zXTOL TEST SATISFIEDizNO FEASIBLE SOLUTIONiz FACTR < 0izFTOL < 0zGTOL < 0zXTOL < 0z STP < STPMINz STP > STPMAXz STPMIN < 0zSTPMAX < STPMINzINITIAL G >= 0zM <= 0zN <= 0z INVALID NBD) iiiiiiiiii gcAgh㈵>g:0yE>i:c 2|r|}d}n|t|}|j}n|}|}t|}| | ||tjt j z|| | | ||d }t||f|||d|}|d|d|d|d|dd }|d }|d }|||fS) 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.18.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.18.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) dispiprintmaxcorftolgtolepsmaxfunmaxitercallbackmaxls)argsjacboundsr7messagenfevnitstatus)gradtaskfuncallsr;warnflagfunx)r derivativer npfinfofloatr1_minimize_lbfgsb)funcx0fprimer6 approx_gradr8mfactrpgtolepsilonr-r2r3r,r4r5rAr7optsresdfrBs _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/optimize/_lbfgsb_py.pyrr^sH nnh'HBHHUO///  D 3 #3v #! #CUY[E ]  $A E A CA a7Ng#>c t||}|}|tjtjz }t |j }|j\}|turtjdtd| turtjdtd|nxt||k7r tdtjt|}|d|dkDj!r tdtj"||d|d}t%||||| ||| }|j&}t)|tj*}t)|t,}t)|t,}tj. tj.fddtj.fdd d tj. dfdi}|at1d|D]R}|d|f|d|f}}tj2|s|||<d}tj2|s|||<d}|||f||<T|dkDs td t|tj, }tdtj, } t)|ftj, }!t)d |z|zd|zzd|z|zzd|zzt,}"t)d|ztj* }#t)d tj* }$t)d tj* }%t)dtj* }&t)dtj* }'t)dt, }(d}) |!j5tj,}!t7j8|||||| |!|||"|#|$|&|'|(||%|$ddk(r ||\} }!n[|$ddk(rR|)dz })t;|| }*t=| |*r d|$d<d|$d<|)| k\r d|$d<d|$d<n|j>| kDr d|$d<d|$d<nn|$ddk(rd}+n|j>| kDs|)| k\rd}+nd }+|"d||zjA||},|"||zd |z|zjA||}-|'d}.tC|.|}/tE|,d|/|-d|/}0tF|$ddztH|$dz}1t;| |!|j>|jJ|)|+|1||+dk(|0 S)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.18.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 before minimization terminates. Note that this function may violate the limit if the gradients are evaluated by numerical differentiation. maxiter : int Maximum number of algorithm 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.18.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. workers : int, map-like callable, optional A map-like callable, such as `multiprocessing.Pool.map` for evaluating any numerical differentiation in parallel. This evaluation is carried out as ``workers(fun, iterable)``. .. versionadded:: 1.16.0 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`. If the minimization is slow to converge the optimizer may halt if the total number of function evaluations exceeds `maxfun`, or the number of algorithm iterations has reached `maxiter` (whichever comes first). If this is the case then ``result.success=False``, and an appropriate error message is contained in ``result.message``. zzscipy.optimize: The `disp` and `iprint` options of the L-BFGS-B solver are deprecated and will be removed in SciPy 1.18.0.r) stacklevelNz length of x0 != length of boundsrrz@LBFGSB - one of the lower bounds is greater than an upper bound.)r7r6rOr8finite_diff_rel_stepworkers)rrrzmaxls must be positive.)dtypegr r#r,)rBrAr'r&r%z: ) rAr7r:njevr;r<r9rBsuccesshess_inv)&r rDrErFr1rravelshaperwarningswarnDeprecationWarninglen ValueErrorrranyclipr fun_and_gradrint32rinfrangeisinfastypersetulbr r r:reshapeminrstatus_messages task_messagesngev)2rArIr6r7r8r,r.r/r0r1r2r3r-r4r5rXrYunknown_optionsrLrNrMnsf func_and_gradnbdlow_bnd upper_bnd bounds_mapiLUrBrSgwaiwar>ln_tasklsaveisavedsave n_iterationsintermediate_resultr@syn_bfgs_updatesn_corrsramsgs2 rTrGrG&s^?+A E 288E?&& &E    B BA 8 &)Q 8 X &)Q 8~ V ;<<*623 1Iq ! & & (R  WWRF1I . "#rss)/7K*1 3B OOM 288 CAwGa!IFF7BFF#Qbff+q!FF7A,#J q! &A!Q$<1qA88A; 88A; ! 1%CF & 19233 b #A c$A qd"**%A qs1uqs{RT!V#ac)7 3B !288 $C "(( #DARXX&G !288 $E "BHH %E "G $EL  HHRZZ q!WiaE5"D%ug G 7a< !#DAq !W\ A L"01!"< (3FGQQw&QQ6!QQ = @ Aw!| 6 \W4 1ac 1a A 1Q3!Aq!$A2YN.&)G"1Xg;(7 iN) rcndimrhsuper__init__rDrskykreinsumrho)selfrrrrx __class__s rTrzLbfgsInvHessProduct.__init__s~ 88rxx 277a<OP PXX  rzz!Q8 ryyR44rUcL|j|j|j|jf\}}}}t j ||j d}|jdk(r#|jddk(r|jd}t j|}t|dz ddD]2}||t j|||z||<|||||zz }4|} t|D]2}||t j||| z} | ||||| z zz} 4| S)aEEfficient 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 TrZcopyrr) rrrrrDrrZrrcrremptyrndot) rrBrrrrqalpharrbetas rT_matveczLbfgsInvHessProduct._matvec(s "WWdggt||TXXE1gs HHQdjjt 4 66Q;1771:? " A!wqy"b) "A1vqtQ/E!HE!HQqTM!A " w -Aq6BFF1Q4O+DAaDE!HtO,,A -rUcZ|j|j|j|jf\}}}}t j ||j d}t j||jdf}t|dz ddD]G}||t j|||z||<|||||ddtjfzz}I|} t|D]G}||t j||| z} | ||ddtjf||| z zz } I| S)aEfficient matrix-matrix multiply with the BFGS matrices. This calculation is described in Section (4) of [1]. Parameters ---------- X : ndarray An array with shape (n,m) Returns ------- Y : ndarray The matrix-matrix product Notes ----- This implementation is written starting from _matvec and broadcasting all expressions along the second axis of X. TrrrN) rrrrrDrrZrrcrnrnewaxis) rXrrrrQrrRrs rT_matmatzLbfgsInvHessProduct._matmatJs!*"WWdggt||TXXE1gs HHQdjjt 4'1771:./wqy"b) .A1vqtQ/E!H q!A$q"**}-- -A . w 9Aq6BFF1Q4O+D 1am$a48 8A 9rUcvtj|jd|ji}|j |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`. rZ)rDeyercrZr)rI_arrs rTtodensezLbfgsInvHessProduct.todenseos. 5$**5||E""rU) __name__ __module__ __qualname____doc__rrrr __classcell__)rs@rTrrs2 5 D#J #rU)rnumpyrDrrrrr$r _optimizer r r r r r _constraintsrscipy.sparse.linalgrscipy._lib.deprecationrrd__all__rtrurrGrr(rUrTrsF0022+.+ 1 2   "" /   3   (  6 4 1 # ,..   +!"*#$          7 <$(b3d!%Xr EP$&4"24JD$t2*. XKvy#.y#rU