
    ^MhOj                         d Z ddlmZ ddlmZ ddlZg dZ G d de          Z	d	 Z
	 	 	 	 d dZ	 	 	 d!dZeZ	 	 	 d"dZ	 	 	 	 d#dZd Zd Zd Zd$dZd$dZd%dZ	 d&dZ	 	 d'dZdS )(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                       e Zd ZdS )r   N)__name__
__module____qualname__     Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_linesearch.pyr   r      s        Dr   r   c                 P    d| cxk     r|cxk     rdk     sn t          d          d S )Nr   r   z.'c1' and 'c2' do not satisfy'0 < c1 < c2 < 1'.)
ValueError)c1c2s     r   _check_c1_c2r      sA    OOOOROOOO!OOOO . / / 	/ Or   r   -C6??2   :0yE>+=c                      |	 gR  }|gdgdg fd}fd}t          j        |          }t          |||||||	|
||
  
        \  }}}|d         d         ||d         fS )a1  
    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``.

    Nr   c                 B    dxx         dz  cc<    | z  z   gR  S Nr   r   r   )sargsffcpkxks    r   phizline_search_wolfe1.<locals>.phiR   s8    
1
qad"T""""r   c                 ~     | z  z   gR  d<   dxx         dz  cc<   t          j        d                   S r   npdot)r    r!   fprimegcgvalr$   r%   s    r   derphiz"line_search_wolfe1.<locals>.derphiV   sQ    &ad*T***Q
1
vd1gr"""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 {fR$5D
B
B# # # # # # # # ## # # # # # # # # #
 fS"ooG.<bt$T; ; ;Cx 1r!udHd1g55r   c
           	         t          ||           | | d          }| |d          }|(|dk    r"t          dd||z
  z  |z            }
|
dk     rd}
nd}
d}t          | ||||	||          } ||
|||          \  }}}}|||fS )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.

    N        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 R|s2ww&**1S&$/27:;;A::FGCRtT::F"FT7G  CtT d?r   
   c                 b    dgdgdgdg fd}|fd|	 gR  }t          j        |          }fd}nd}t          ||||||	|
||
  
        \  }}}}|t          dt          d	           nd         }|d         d         |||fS )
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                 B    dxx         dz  cc<    | z  z   gR  S r   r   )alphar!   r"   r#   r$   r%   s    r   r&   zline_search_wolfe2.<locals>.phi  s8    
1
qebj(4((((r   c                     dxx         dz  cc<    | z  z   gR  d<   | d<   t          j        d                   S r   r(   )rH   r!   r+   r,   r-   
gval_alphar$   r%   s    r   r.   z"line_search_wolfe2.<locals>.derphi#  sZ    
1
&ebj04000Q
1vd1gr"""r   c                 j    d         | k    r |            | z  z   } | ||d                   S )Nr   r   )	rH   r&   xr.   extra_conditionr-   rJ   r$   r%   s	      r   extra_condition2z,line_search_wolfe2.<locals>.extra_condition20  sF    !}%%uURZA"?5!S$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/   rM   r>   r&   r5   rN   
alpha_starphi_starderphi_starr.   r#   r+   r,   r-   rJ   s   ` ``   `   `       @@@@@@r   r   r      s   | B
B6DJ) ) ) ) ) ) ) ) ) F# # # # # # # # # # # {fR$fS"ooG"	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;  2F<"b$g3/ 3/ 3//J(K 91	. 	. 	. 	. 	. 1gr!ubeXxDDr   c
                 r   t          ||           | | d          }| |d          }d}
| |dk    rt          dd||z
  z  |z            }nd}|dk     rd}|t          ||          } | |          }|}|}|d }t          |	          D ]}|dk    s|8|
|k    r2d}|}|}d}|dk    rd}ndd	| z   }t          |t          d
            n|dk    }||||z  |z  z   k    s||k    r"|r t          |
||||| ||||||          \  }}} n ||          }t          |          | |z  k    r |||          r|}|}|} no|dk    r t          ||
|||| ||||||          \  }}} nId
|z  }|t          ||          }|}
|}|} | |          }|}|}|}d}t          dt          d
           ||||fS )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                     dS )NTr   )rH   r&   s     r   rM   z-scalar_search_wolfe2.<locals>.extra_condition  s    4r   z7Rounding errors prevent the line search from convergingz4The line search algorithm could not find a solution zless than or equal to amax: rP   rQ   rO   )r   r?   ranger   r   _zoomabs)r&   r.   r=   r@   r5   r   r   r/   rM   r>   alpha0rA   phi_a1phi_a0	derphi_a0irT   rU   rV   msgnot_first_iteration	derphi_a1alpha2s                          r   r
   r
   I  s   p R|s2ww&**F1S&$/27:;;zzVT""S[[F FI	 	 	 7^^ 9. 9.Q;;4+ JHDK{{OL;T;;< 'A6666E!eTBK'1111v#6fff$if"GR_F F .J+ EF6NN		NNrc'k))vv.. #
!'NNfff$if"GR_F F .J+ EV&&FV		 
91	. 	. 	. 	. x{22r   c           
         t          j        ddd          5  	 |}|| z
  }|| z
  }	||	z  dz  ||	z
  z  }
t          j        d          }|	dz  |d<   |dz   |d<   |	dz   |d<   |dz  |d	<   t          j        |t          j        ||z
  ||z  z
  ||z
  ||	z  z
  g                                                    \  }}||
z  }||
z  }||z  d|z  |z  z
  }| | t          j        |          z   d|z  z  z   }n# t          $ r Y d
d
d
           d
S w xY w	 d
d
d
           n# 1 swxY w Y   t          j        |          sd
S |S )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invalidrP   )rP   rP   )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     s    
G'7	C	C	C  	AQBQB"WNb2g.E&!!BQwBtHaxBtHaxBtHQwBtHVB
BGa"f,<,.Ga"f,<,> !? !??FwyyJ JFQJAJA!ea!eai'GRWW---!a%88DD 	 	 	%       "	 !              & ;t tKs5   DCC43D4
D>DDDD!$D!c                    t          j        ddd          5  	 |}|}|| dz  z
  }||z
  ||z  z
  ||z  z  }| |d|z  z  z
  }	n# t          $ r Y ddd           dS w xY w	 ddd           n# 1 swxY w Y   t          j        |	          sdS |	S )z
    Finds the minimizer for a quadratic polynomial that goes through
    the points (a,fa), (b,fb) with derivative at a of fpa.

    rf   rg   r:          @N)r)   rl   rq   rr   )
rs   rt   ru   rv   rw   Dry   rz   r   r   s
             r   _quadminr     s#    
G'7	C	C	C  	AAQWBa!b&R"W-AqC!G}$DD 	 	 	       	                ;t tKs4   A,(AA,
AA,AA,,A03A0c           	      L   d}d}d}d}|}d}	 || z
  }|dk     r|| }}n| |}}|dk    r||z  }t          | ||||||          }|dk    s||||z
  k    s	|||z   k     r4||z  }t          | ||||          }||||z
  k    s	|||z   k     r| d|z  z   } ||          }|||	|z  |z  z   k    s||k    r	|}|}|}|}nT ||          }t          |          |
 |z  k    r |||          r|}|}|}n3||| z
  z  dk    r	|}|}| }|}n|}| }|} |}|}|dz  }||k    rd}d}d}n|||fS )	a  Zoom 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.

    rE   r   g?皙?TN      ?r   )r   r   r[   )a_loa_hiphi_lophi_hi	derphi_lor&   r.   r=   r5   r   r   rM   r>   r`   delta1delta2phi_reca_recdalphars   rv   cchka_jqchkphi_aj	derphi_aja_starval_starvalprime_stars                                r   rZ   rZ     s    G	AFFGE@ A::qAAqA EEF?DD&)T6!7, ,CFFq4xS1t8^^F?D4D&AACqv34<<SZ' STBsF7N***&0@0@GEDFFsI9~~"W,,f1M1M,! )$+&!++  DF!I	QKKFH MA@B 8]**r   c                      t          j                  dg fd}| |d          }	n|}	t          j        |          }
t          ||	|
||          \  }}|d         |fS )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                 B    dxx         dz  cc<    | z  z   gR  S r   r   )rA   r!   r"   r#   r$   r%   s    r   r&   zline_search_armijo.<locals>.phi  s8    
1
qfRi'$''''r   Nr9   )r   r\   )r)   
atleast_1dr*   scalar_search_armijo)r"   r%   r$   r2   r3   r!   r   r\   r&   r=   r5   rH   rC   r#   s   ```  `       @r   r   r   o  s    D 
r		B
B( ( ( ( ( ( ( ( ( s2wwfS"ooG&sD'b.46 6 6KE4"Q%r   c           
      `    t          | |||||||          }|d         |d         d|d         fS )z8
    Compatibility wrapper for `line_search_armijo`
    )r!   r   r\   r   r   rP   )r   )	r"   r%   r$   r2   r3   r!   r   r\   rs	            r   line_search_BFGSr     sD     	1b"c8$2"(	* 	* 	*AQ41q!A$r   c                     | |          }||||z  |z  z   k    r||fS | |dz  z  dz  ||z
  ||z  z
  z  } | |          }||||z  |z  z   k    r||fS ||k    r|dz  |dz  z  ||z
  z  }	|dz  ||z
  ||z  z
  z  |dz  ||z
  ||z  z
  z  z
  }
|
|	z  }
|dz   ||z
  ||z  z
  z  |dz  ||z
  ||z  z
  z  z   }||	z  }| t          j        t          |dz  d|
z  |z  z
                      z   d|
z  z  } | |          }||||z  |z  z   k    r||fS ||z
  |dz  k    sd||z  z
  dk     r|dz  }|}|}|}|}||k    d|fS )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

    rP   r   rk   g      @r   gQ?N)r)   rp   r[   )r&   r=   r5   r   r\   r0   r^   rA   r]   factorrs   rv   rd   phi_a2s                 r   r   r     s    S[[F6	'))))v~ Z&!)#c)Vd]Wv=M-MNFS[[F$F7****v~ 4--VQY&&-8AI$78AI$789JQYJ&4-'&.89AI$789J"rws1a4!a%'/#9::;;;AFVdRYw....6>!VOv|++F6M0AT/I/Ic\F+ 4--0 <r   r   r   c                    |d         }t          |          }	d}
d}d}	 ||
|z  z   } | |          \  }}||	|z   ||
dz  z  |z  z
  k    r|
}n|
dz  |z  |d|
z  dz
  |z  z   z  }|||z  z
  } | |          \  }}||	|z   ||dz  z  |z  z
  k    r| }nP|dz  |z  |d|z  dz
  |z  z   z  }t          j        |||
z  ||
z            }
t          j        |||z  ||z            }||||fS )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   TrP   )maxr)   clip)r"   x_kdprev_fsetagammatau_mintau_maxf_kf_baralpha_palpha_mrH   xpfpFpalpha_tpalpha_tms                     r   _nonmonotone_line_search_cruzr     s]   P "+CLLEGGEJ7Q;2Buwz1C7777EA:#rQwY]C,?'?@7Q;2Buwz1C7777HEA:#rQwY]C,?'?@'(Gg$5w7HII'(Gg$5w7HII)J, "b"r   333333?c                    d}d}d}	 |||z  z   } | |          \  }}|||z   ||dz  z  |z  z
  k    r|}n|dz  |z  |d|z  dz
  |z  z   z  }|||z  z
  } | |          \  }}|||z   ||dz  z  |z  z
  k    r| }nP|dz  |z  |d|z  dz
  |z  z   z  }t          j        |||z  |	|z            }t          j        |||z  |	|z            }|
|z  dz   }|
|z  ||z   z  |z   |z  }|}||||||fS )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   TrP   )r)   r   )r"   r   r   r   ry   Qr   r   r   r   nur   r   rH   r   r   r   r   r   Q_nexts                       r   _nonmonotone_line_search_chengr   2  s{   ^ GGEJ7Q;2BS57A:-3333EA:#rQwY]C,?'?@7Q;2BS57A:-3333HEA:#rQwY]C,?'?@'(Gg$5w7HII'(Gg$5w7HII)J. !VaZF	a1s7	b	 F*AA"b"a""r   )	NNNr   r   r   r   r   r   )NNNr   r   r   r   r   )	NNNr   r   r   NNrE   )NNNr   r   NNrE   )r   r   r   )r   r   r   )r   r   r   )r   r   r   r   )__doc__warningsr   _dcsrchr   numpyr)   __all__RuntimeWarningr   r   r   r	   line_searchr   r
   r   r   rZ   r   r   r   r   r   r   r   r   <module>r      s                   ! ! !	 	 	 	 	 	 	 	/ / / /337?C!<6 <6 <6 <6~ IM%(27J J J JZ ! @DIM57LE LE LE LE^ ,004/379Q3 Q3 Q3 Q3h  D  *T+ T+ T+v1 1 1 1h   7 7 7 7~ DGE E E ER EH&*N# N# N# N# N# N#r   