
    (phOj                         S r SSKJr  SSKJr  SSKr/ SQr " S S\5      r	S	 r
    SS
 jr   SS jr\r   SS jr    SS jrS rS rS rSS jrSS jrSS jr SS jr  SS jrg)z
Functions
---------
.. autosummary::
   :toctree: generated/

    line_search_armijo
    line_search_wolfe1
    line_search_wolfe2
    scalar_search_wolfe1
    scalar_search_wolfe2

    )warn   )DCSRCHN)LineSearchWarningline_search_wolfe1line_search_wolfe2scalar_search_wolfe1scalar_search_wolfe2line_search_armijoc                       \ rS rSrSrg)r       N)__name__
__module____qualname____firstlineno____static_attributes__r       M/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_linesearch.pyr   r      s    r   r   c                 F    SU s=:  a  Us=:  a  S:  d  O  [        S5      eg )Nr   r   z.'c1' and 'c2' do not satisfy'0 < c1 < c2 < 1'.)
ValueError)c1c2s     r   _check_c1_c2r      s(    ORO!O . / 	/ r   c                    ^ ^^^^^^^ Uc	  T" T/TQ76 nU/mS/mS/mUU UUU4S jnUUUUUU4S jn[         R                  " UT5      n[        XXVUXXUS9
u  nnnUTS   TS   UUTS   4$ )a  
As `scalar_search_wolfe1` but do a line search to direction `pk`

Parameters
----------
f : callable
    Function `f(x)`
fprime : callable
    Gradient of `f`
xk : array_like
    Current point
pk : array_like
    Search direction
gfk : array_like, optional
    Gradient of `f` at point `xk`
old_fval : float, optional
    Value of `f` at point `xk`
old_old_fval : float, optional
    Value of `f` at point preceding `xk`

The rest of the parameters are the same as for `scalar_search_wolfe1`.

Returns
-------
stp, f_count, g_count, fval, old_fval
    As in `line_search_wolfe1`
gval : array
    Gradient of `f` at the final point

Notes
-----
Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.

r   c                 <   > TS==   S-  ss'   T" TU T-  -   /TQ76 $ Nr   r   r   )sargsffcpkxks    r   philine_search_wolfe1.<locals>.phiR   s(    
1
ad"T""r   c                 v   > T" TU T-  -   /TQ76 TS'   TS==   S-  ss'   [         R                  " TS   T5      $ r   npdot)r   r   fprimegcgvalr"   r#   s    r   derphi"line_search_wolfe1.<locals>.derphiV   s@    ad*T*Q
1
vvd1gr""r   )r   r   amaxaminxtol)r(   r)   r	   )r    r*   r#   r"   gfkold_fvalold_old_fvalr   r   r   r/   r0   r1   r$   r-   derphi0stpfvalr!   r+   r,   s   ````   `          @@@r   r   r   %   s    L {R$5D
B
B# ## #
 ffS"oG.tT;Cx 1r!udHd1g55r   c
           	          [        XV5        Uc  U " S5      nUc  U" S5      nUb#  US:w  a  [        SSX#-
  -  U-  5      n
U
S:  a  Sn
OSn
Sn[        XXVXU5      nU" XXKS9u  pp/XU4$ )a  
Scalar function search for alpha that satisfies strong Wolfe conditions

alpha > 0 is assumed to be a descent direction.

Parameters
----------
phi : callable phi(alpha)
    Function at point `alpha`
derphi : callable phi'(alpha)
    Objective function derivative. Returns a scalar.
phi0 : float, optional
    Value of phi at 0
old_phi0 : float, optional
    Value of phi at previous point
derphi0 : float, optional
    Value derphi at 0
c1 : float, optional
    Parameter for Armijo condition rule.
c2 : float, optional
    Parameter for curvature condition rule.
amax, amin : float, optional
    Maximum and minimum step size
xtol : float, optional
    Relative tolerance for an acceptable step.

Returns
-------
alpha : float
    Step size, or None if no suitable step was found
phi : float
    Value of `phi` at the new point `alpha`
phi0 : float
    Value of `phi` at `alpha=0`

Notes
-----
Uses routine DCSRCH from MINPACK.

Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1`` as described in [1]_.

References
----------

.. [1] Nocedal, J., & Wright, S. J. (2006). Numerical optimization.
   In Springer Series in Operations Research and Financial Engineering.
   (Springer Series in Operations Research and Financial Engineering).
   Springer Nature.

        r         ?)\( @d   )phi0r5   maxiter)r   minr   )r$   r-   r=   old_phi0r5   r   r   r/   r0   r1   alpha1r>   dcsrchr6   phi1tasks                   r   r	   r	   d   s    j |2w*1S&$/27:;A:FGCT:F"7Ct d?r   c                 :  ^ ^^^^^^^^^^ S/mS/mS/mS/mUU UUU4S jnUmUUUUUUU4S jmUc	  T" T/TQ76 n[         R                  " UT5      nTb  UUUUUU4S jnOSn[        UTXVXXXS9
u  nnnnUc  [        S[        SS	9  OTS   nUTS   TS   UUU4$ )
a  Find alpha that satisfies strong Wolfe conditions.

Parameters
----------
f : callable f(x,*args)
    Objective function.
myfprime : callable f'(x,*args)
    Objective function gradient.
xk : ndarray
    Starting point.
pk : ndarray
    Search direction. The search direction must be a descent direction
    for the algorithm to converge.
gfk : ndarray, optional
    Gradient value for x=xk (xk being the current parameter
    estimate). Will be recomputed if omitted.
old_fval : float, optional
    Function value for x=xk. Will be recomputed if omitted.
old_old_fval : float, optional
    Function value for the point preceding x=xk.
args : tuple, optional
    Additional arguments passed to objective function.
c1 : float, optional
    Parameter for Armijo condition rule.
c2 : float, optional
    Parameter for curvature condition rule.
amax : float, optional
    Maximum step size
extra_condition : callable, optional
    A callable of the form ``extra_condition(alpha, x, f, g)``
    returning a boolean. Arguments are the proposed step ``alpha``
    and the corresponding ``x``, ``f`` and ``g`` values. The line search
    accepts the value of ``alpha`` only if this
    callable returns ``True``. If the callable returns ``False``
    for the step length, the algorithm will continue with
    new iterates. The callable is only called for iterates
    satisfying the strong Wolfe conditions.
maxiter : int, optional
    Maximum number of iterations to perform.

Returns
-------
alpha : float or None
    Alpha for which ``x_new = x0 + alpha * pk``,
    or None if the line search algorithm did not converge.
fc : int
    Number of function evaluations made.
gc : int
    Number of gradient evaluations made.
new_fval : float or None
    New function value ``f(x_new)=f(x0+alpha*pk)``,
    or None if the line search algorithm did not converge.
old_fval : float
    Old function value ``f(x0)``.
new_slope : float or None
    The local slope along the search direction at the
    new value ``<myfprime(x_new), pk>``,
    or None if the line search algorithm did not converge.


Notes
-----
Uses the line search algorithm to enforce strong Wolfe
conditions. See Wright and Nocedal, 'Numerical Optimization',
1999, pp. 59-61.

The search direction `pk` must be a descent direction (e.g.
``-myfprime(xk)``) to find a step length that satisfies the strong Wolfe
conditions. If the search direction is not a descent direction (e.g.
``myfprime(xk)``), then `alpha`, `new_fval`, and `new_slope` will be None.

Examples
--------
>>> import numpy as np
>>> from scipy.optimize import line_search

A objective function and its gradient are defined.

>>> def obj_func(x):
...     return (x[0])**2+(x[1])**2
>>> def obj_grad(x):
...     return [2*x[0], 2*x[1]]

We can find alpha that satisfies strong Wolfe conditions.

>>> start_point = np.array([1.8, 1.7])
>>> search_gradient = np.array([-1.0, -1.0])
>>> line_search(obj_func, obj_grad, start_point, search_gradient)
(1.0, 2, 1, 1.1300000000000001, 6.13, [1.6, 1.4])

r   Nc                 <   > TS==   S-  ss'   T" TU T-  -   /TQ76 $ r   r   )alphar   r    r!   r"   r#   s    r   r$   line_search_wolfe2.<locals>.phi  s(    
1
ebj(4((r   c                    > TS==   S-  ss'   T" TU T-  -   /TQ76 TS'   U TS'   [         R                  " TS   T5      $ r   r'   )rG   r   r*   r+   r,   
gval_alphar"   r#   s    r   r-   "line_search_wolfe2.<locals>.derphi#  sI    
1
ebj040Q
1vvd1gr""r   c                 P   > TS   U :w  a  T" U 5        TU T-  -   nT" XUTS   5      $ )Nr   r   )	rG   r$   xr-   extra_conditionr,   rJ   r"   r#   s	      r   extra_condition2,line_search_wolfe2.<locals>.extra_condition20  s6    !}%uURZA"5S$q'::r   )r>   *The line search algorithm did not converge   
stacklevel)r(   r)   r
   r   r   )r    myfprimer#   r"   r2   r3   r4   r   r   r   r/   rN   r>   r$   r5   rO   
alpha_starphi_starderphi_starr-   r!   r*   r+   r,   rJ   s   ` ``   `   `       @@@@@@r   r   r      s    | B
B6DJ) ) F# # {R$ffS"oG"	; 	;  2Fb3//J(K 91	. 1gr!ubeXxDDr   c
                    [        XV5        Uc  U " S5      nUc  U" S5      nSn
Ub  US:w  a  [        SSX#-
  -  U-  5      nOSnUS:  a  SnUb  [        X5      nU " U5      nUnUnUc  S n[        U	5       H  nUS:X  d  Ub/  X:  a*  SnUnUnSnUS:X  a  SnOSS	U 3-   n[        U[        S
S9    OUS:  nXX[-  U-  -   :  d  X:  a  U(       a  [        XUXXX$XVU5      u  nnn  OU" U5      n[        U5      U* U-  ::  a  U" X5      (       a  UnUnUn  O[US:  a  [        XUUUXX$XVU5      u  nnn  O=S
U-  nUb  [        UU5      nUn
UnUnU " U5      nUnM     UnUnSn[        S[        S
S9  UUUU4$ )a  Find alpha that satisfies strong Wolfe conditions.

alpha > 0 is assumed to be a descent direction.

Parameters
----------
phi : callable phi(alpha)
    Objective scalar function.
derphi : callable phi'(alpha)
    Objective function derivative. Returns a scalar.
phi0 : float, optional
    Value of phi at 0.
old_phi0 : float, optional
    Value of phi at previous point.
derphi0 : float, optional
    Value of derphi at 0
c1 : float, optional
    Parameter for Armijo condition rule.
c2 : float, optional
    Parameter for curvature condition rule.
amax : float, optional
    Maximum step size.
extra_condition : callable, optional
    A callable of the form ``extra_condition(alpha, phi_value)``
    returning a boolean. The line search accepts the value
    of ``alpha`` only if this callable returns ``True``.
    If the callable returns ``False`` for the step length,
    the algorithm will continue with new iterates.
    The callable is only called for iterates satisfying
    the strong Wolfe conditions.
maxiter : int, optional
    Maximum number of iterations to perform.

Returns
-------
alpha_star : float or None
    Best alpha, or None if the line search algorithm did not converge.
phi_star : float
    phi at alpha_star.
phi0 : float
    phi at 0.
derphi_star : float or None
    derphi at alpha_star, or None if the line search algorithm
    did not converge.

Notes
-----
Uses the line search algorithm to enforce strong Wolfe
conditions. See Wright and Nocedal, 'Numerical Optimization',
1999, pp. 59-61.

Nr9   r   r:   r;   c                     g)NTr   )rG   r$   s     r   rN   -scalar_search_wolfe2.<locals>.extra_condition  s    r   z7Rounding errors prevent the line search from convergingz4The line search algorithm could not find a solution zless than or equal to amax: rR   rS   rQ   )r   r?   ranger   r   _zoomabs)r$   r-   r=   r@   r5   r   r   r/   rN   r>   alpha0rA   phi_a1phi_a0	derphi_a0irV   rW   rX   msgnot_first_iteration	derphi_a1alpha2s                          r   r
   r
   I  s   p |2w*F1S&$/27:;zV"[F FI	 7^Q;4+ JHDK{OL4TF;< 'A6!eBK'111#6ff$"R_F .J+ 6N		Nrc'k)v..#
!'Nff$i"R_F .J+ V&FV	c j 
91	. x{22r   c           
      r   [         R                  " SSSS9    UnX0-
  nXP-
  n	X-  S-  X-
  -  n
[         R                  " S5      nU	S-  US'   US-  * US'   U	S-  * US'   US-  US	'   [         R                  " U[         R                  " XA-
  Xx-  -
  Xa-
  Xy-  -
  /5      R                  5       5      u  pX-  nX-  nX-  SU-  U-  -
  nX* [         R                  " U5      -   SU-  -  -   n S
S
S
5        [         R                  " W5      (       d  g
U$ ! [         a     S
S
S
5        g
f = f! , (       d  f       ND= f)z
Finds the minimizer for a cubic polynomial that goes through the
points (a,fa), (b,fb), and (c,fc) with derivative at a of fpa.

If no minimizer can be found, return None.

raisedivideoverinvalidrR   )rR   rR   )r   r   )r   r      )r   r   )r   r   N)	r(   errstateemptyr)   asarrayflattensqrtArithmeticErrorisfinite)afafpabfbcr!   Cdbdcdenomd1ABradicalxmins                   r   	_cubicminr     sN    
G'7	C	ABBWNbg.E&!BQwBtHaxBtHaxBtHQwBtHVVB

BGaf,<,.Gaf,<,> !??FwyJFQJAJAea!eai'GRWWW--!a%88D! 
D& ;;tK	  	% 
D	C"	# 
D	Cs)   D(CD
D%D($D%%D((
D6c                    [         R                  " SSSS9    UnUnX0S-  -
  nXE-
  Xg-  -
  Xw-  -  nXSU-  -  -
  n	 SSS5        [         R                  " W	5      (       d  gU	$ ! [         a     SSS5        gf = f! , (       d  f       ND= f)zz
Finds the minimizer for a quadratic polynomial that goes through
the points (a,fa), (b,fb) with derivative at a of fpa.

ri   rj   r:          @N)r(   ro   rt   ru   )
rv   rw   rx   ry   rz   Dr|   r}   r   r   s
             r   _quadminr     s     
G'7	C	AAWB!&RW-AC!G}$D 
D ;;tK	  	 
D	C	 
D	Cs(   A;#A##
A8-A;7A88A;;
B	c           	         SnSnSnSnUnSn X-
  nUS:  a  XnnOXnnUS:  a  UU-  n[        XXAUUU5      nUS:X  d  Wb  UUW-
  :  d	  UUU-   :  a/  UU-  n[        XXAU5      nUb  UUU-
  :  d	  UUU-   :  a  U SU-  -   nU" U5      nUXyU-  U-  -   :  d  UU:  a	  UnUnUnUnONU" U5      n[        U5      U
* U-  ::  a  U" UU5      (       a  UnUnUnO1UX-
  -  S:  a	  UnUnU nUnOUnU nUn UnUnUS-  nX:  a  SnSnSnOM  UUU4$ )zZoom stage of approximate linesearch satisfying strong Wolfe conditions.

Part of the optimization algorithm in `scalar_search_wolfe2`.

Notes
-----
Implements Algorithm 3.6 (zoom) in Wright and Nocedal,
'Numerical Optimization', 1999, pp. 61.


   r   g?皙?N      ?r   )r   r   r^   )a_loa_hiphi_lophi_hi	derphi_lor$   r-   r=   r5   r   r   rN   r>   rc   delta1delta2phi_reca_recdalpharv   ry   cchka_jqchkphi_aj	derphi_aja_starval_starvalprime_stars                                r   r]   r]     s    G	AFFGE
 A:qAqqA EF?DD)6!7,CFq4xS1t8^F?D4&ACqv34<SZ' STsF7N**&0@GEDFsI9~"W,f1M1M! )$+&!+  DF!I	QKFH MA B 8]**r   c                    ^ ^^^^ [         R                  " T5      mS/mUU UUU4S jnUc	  U" S5      n	OUn	[         R                  " UT5      n
[        XXUS9u  pUTS   U4$ )a  Minimize over alpha, the function ``f(xk+alpha pk)``.

Parameters
----------
f : callable
    Function to be minimized.
xk : array_like
    Current point.
pk : array_like
    Search direction.
gfk : array_like
    Gradient of `f` at point `xk`.
old_fval : float
    Value of `f` at point `xk`.
args : tuple, optional
    Optional arguments.
c1 : float, optional
    Value to control stopping criterion.
alpha0 : scalar, optional
    Value of `alpha` at start of the optimization.

Returns
-------
alpha
f_count
f_val_at_alpha

Notes
-----
Uses the interpolation algorithm (Armijo backtracking) as suggested by
Wright and Nocedal in 'Numerical Optimization', 1999, pp. 56-57

r   c                 <   > TS==   S-  ss'   T" TU T-  -   /TQ76 $ r   r   )rA   r   r    r!   r"   r#   s    r   r$   line_search_armijo.<locals>.phi  s(    
1
fRi'$''r   r9   )r   r_   )r(   
atleast_1dr)   scalar_search_armijo)r    r#   r"   r2   r3   r   r   r_   r$   r=   r5   rG   rC   r!   s   ```  `       @r   r   r   o  sn    D 
r	B
B( ( 2wffS"oG&s'.46KE"Q%r   c                 :    [        XX#XEUUS9nUS   US   SUS   4$ )z0
Compatibility wrapper for `line_search_armijo`
)r   r   r_   r   r   rR   )r   )	r    r#   r"   r2   r3   r   r   r_   rs	            r   line_search_BFGSr     s4     	1"82"(	*AQ41q!A$r   c                 <   U " U5      nXaX4-  U-  -   ::  a  XF4$ U* US-  -  S-  Xa-
  X$-  -
  -  nU " U5      nXX7-  U-  -   ::  a  Xx4$ Xu:  a  US-  US-  -  Xt-
  -  n	US-  X-
  X'-  -
  -  US-  Xa-
  X$-  -
  -  -
  n
X-  n
US-  * X-
  X'-  -
  -  US-  Xa-
  X$-  -
  -  -   nX-  nU* [         R                  " [        US-  SU
-  U-  -
  5      5      -   SU
-  -  nU " U5      nXX<-  U-  -   ::  a  X4$ X|-
  US-  :  d  SX-  -
  S:  a  US-  nUnUnUnUnXu:  a  M  SU4$ )a  Minimize over alpha, the function ``phi(alpha)``.

Uses the interpolation algorithm (Armijo backtracking) as suggested by
Wright and Nocedal in 'Numerical Optimization', 1999, pp. 56-57

alpha > 0 is assumed to be a descent direction.

Returns
-------
alpha
phi1

rR   r   rn   g      @r   gQ?N)r(   rs   r^   )r$   r=   r5   r   r_   r0   ra   rA   r`   factorrv   ry   rg   phi_a2s                 r   r   r     s    [F	')))~ Z&!)#c)V]W=M-MNF[F7***~ -VQY&&-8AI78AI789JQYJ&-'.89AI789J"rwws1a4!a%'/#9:;;AFVRYw...>!Ov|+FM0AT/Ic\F+ -0 <r   c                    US   n[        U5      n	Sn
SnSn XU-  -   nU " U5      u  pXU-   XZS-  -  U-  -
  ::  a  U
nOU
S-  U-  USU
-  S-
  U-  -   -  nXU-  -
  nU " U5      u  pXU-   X[S-  -  U-  -
  ::  a  U* nOQUS-  U-  USU-  S-
  U-  -   -  n[        R                  " UXj-  Xz-  5      n
[        R                  " UXk-  X{-  5      nM  XX4$ )a  
Nonmonotone backtracking line search as described in [1]_

Parameters
----------
f : callable
    Function returning a tuple ``(f, F)`` where ``f`` is the value
    of a merit function and ``F`` the residual.
x_k : ndarray
    Initial position.
d : ndarray
    Search direction.
prev_fs : float
    List of previous merit function values. Should have ``len(prev_fs) <= M``
    where ``M`` is the nonmonotonicity window parameter.
eta : float
    Allowed merit function increase, see [1]_
gamma, tau_min, tau_max : float, optional
    Search parameters, see [1]_

Returns
-------
alpha : float
    Step length
xp : ndarray
    Next position
fp : float
    Merit function value at next position
Fp : ndarray
    Residual at next position

References
----------
[1] "Spectral residual method without gradient information for solving
    large-scale nonlinear systems of equations." W. La Cruz,
    J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006).

r   rR   )maxr(   clip)r    x_kdprev_fsetagammatau_mintau_maxf_kf_baralpha_palpha_mrG   xpfpFpalpha_tpalpha_tms                     r   _nonmonotone_line_search_cruzr     s+   P "+CLEGGE
Q;2uz1C777EA:#rQwY]C,?'?@Q;2uz1C777HEA:#rQwY]C,?'?@''(G$5w7HI''(G$5w7HI) , br   c                    SnSnSn XU-  -   nU " U5      u  nnXU-   X{S-  -  U-  -
  ::  a  UnOUS-  U-  USU-  S-
  U-  -   -  nXU-  -
  nU " U5      u  nnXU-   X|S-  -  U-  -
  ::  a  U* nOQUS-  U-  USU-  S-
  U-  -   -  n[         R                  " UX-  X-  5      n[         R                  " UX-  X-  5      nM  X-  S-   nX-  XF-   -  U-   U-  nUnXUUXE4$ )a  
Nonmonotone line search from [1]

Parameters
----------
f : callable
    Function returning a tuple ``(f, F)`` where ``f`` is the value
    of a merit function and ``F`` the residual.
x_k : ndarray
    Initial position.
d : ndarray
    Search direction.
f_k : float
    Initial merit function value.
C, Q : float
    Control parameters. On the first iteration, give values
    Q=1.0, C=f_k
eta : float
    Allowed merit function increase, see [1]_
nu, gamma, tau_min, tau_max : float, optional
    Search parameters, see [1]_

Returns
-------
alpha : float
    Step length
xp : ndarray
    Next position
fp : float
    Merit function value at next position
Fp : ndarray
    Residual at next position
C : float
    New value for the control parameter C
Q : float
    New value for the control parameter Q

References
----------
.. [1] W. Cheng & D.-H. Li, ''A derivative-free nonmonotone line
       search and its application to the spectral residual
       method'', IMA J. Numer. Anal. 29, 814 (2009).

r   rR   )r(   r   )r    r   r   r   r|   Qr   r   r   r   nur   r   rG   r   r   r   r   r   Q_nexts                       r   _nonmonotone_line_search_chengr   2  sI   ^ GGE
Q;2BS5A:-333EA:#rQwY]C,?'?@Q;2BS5A:-333HEA:#rQwY]C,?'?@''(G$5w7HI''(G$5w7HI) . VaZF	17	b	 F*AAb"a""r   )	NNNr   -C6??2   :0yE>+=)NNNr   r   r   r   r   )	NNNr   r   r   NNr   )NNNr   r   NNr   )r   r   r   )r   r   r   )r   r   r   )r   r   r   g333333?)__doc__warningsr   _dcsrchr   numpyr(   __all__RuntimeWarningr   r   r   r	   line_searchr   r
   r   r   r]   r   r   r   r   r   r   r   r   <module>r      s      !	 	/ /337?C!<6~ IM%(27JZ ! @DIM57LE^ ,004/379Q3hD*T+v1h7~ DGER EH&*N#r   