o
    Ö­jÄ  ã                   @   s„   d Z ddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
 G dd„ deƒZ			ddd„Zddd„Zddd„Zdd„ Zdd„ ZdS )z,
Spectral Algorithm for Nonlinear Equations
é    N)ÚOptimizeResult)Ú_check_unknown_optionsé   )Ú_nonmonotone_line_search_cruzÚ_nonmonotone_line_search_chengc                   @   s   e Zd ZdS )Ú_NoConvergenceN)Ú__name__Ú
__module__Ú__qualname__© r   r   úU/var/www/html/CropPilot/venv/lib/python3.10/site-packages/scipy/optimize/_spectral.pyr      s    r   r   ç:Œ0âŽyE>çYóøÂn¥éè  Fé
   ç»½×Ùß|Û=ç      ð?Úcruzc           *   	      s2  t |ƒ |dvrtd|›d�ƒ‚d‰|
du r‡ fdd„}
|du r'‡‡fdd	„}‡fd
d„}dg}t| |||||ƒ\}}}‰}}d}ˆ‰ |}||ƒ}t ˆg|	¡}d}ˆ }d}d}	 ||ƒ}|rhtd|||f ƒ |durq|||ƒ ||| | k r~d}d}n€t|ƒd| kr�d| t |¡ }nt|ƒ|k r˜|}| | }|
|||ƒ} z)|dkr¶t	||||| d�\}!}"}#}$n|dkrËt
|||ˆ||| d�\}!}"}#}$}}W n	 tyÕ   Y n)w |"| }%|$| }&t |%|%¡t |%|&¡ }|"}|$}|#‰|dkrù| |#¡ |d7 }qYt|||d�}'t||ƒ}(t|'|||(|d |dd�})|)S )a›  
    Solve nonlinear equation with the DF-SANE method

    Options
    -------
    ftol : float, optional
        Relative norm tolerance.
    fatol : float, optional
        Absolute norm tolerance.
        Algorithm terminates when ``||func(x)|| < fatol + ftol ||func(x_0)||``.
    fnorm : callable, optional
        Norm to use in the convergence check. If None, 2-norm is used.
    maxfev : int, optional
        Maximum number of function evaluations.
    disp : bool, optional
        Whether to print convergence process to stdout.
    eta_strategy : callable, optional
        Choice of the ``eta_k`` parameter, which gives slack for growth
        of ``||F||**2``.  Called as ``eta_k = eta_strategy(k, x, F)`` with
        `k` the iteration number, `x` the current iterate and `F` the current
        residual. Should satisfy ``eta_k > 0`` and ``sum(eta, k=0..inf) < inf``.
        Default: ``||F||**2 / (1 + k)**2``.
    sigma_eps : float, optional
        The spectral coefficient is constrained to ``sigma_eps < sigma < 1/sigma_eps``.
        Default: 1e-10
    sigma_0 : float, optional
        Initial spectral coefficient.
        Default: 1.0
    M : int, optional
        Number of iterates to include in the nonmonotonic line search.
        Default: 10
    line_search : {'cruz', 'cheng'}
        Type of line search to employ. 'cruz' is the original one defined in
        [Martinez & Raydan. Math. Comp. 75, 1429 (2006)], 'cheng' is
        a modified search defined in [Cheng & Li. IMA J. Numer. Anal. 29, 814 (2009)].
        Default: 'cruz'

    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).
    .. [2] W. La Cruz, Opt. Meth. Software, 29, 24 (2014).
    .. [3] W. Cheng, D.-H. Li. IMA J. Numer. Anal. **29**, 814 (2009).

    )Úchengr   zInvalid value z for 'line_search'é   Nc                    s   ˆ d|  d  S )Nr   r   r   )ÚkÚxÚF)Úf_0r   r   Úeta_strategyJ   s   z#_root_df_sane.<locals>.eta_strategyc                    s   ˆ dˆ  S )Nr   r   ©r   )Úf_kÚnexpr   r   ÚfnormO   s   z_root_df_sane.<locals>.fnormc                    s   t j | ¡ˆ  S ©N)ÚnpÚlinalgÚnormr   )r   r   r   ÚfmeritS   s   z_root_df_sane.<locals>.fmeritr   r   Fz&too many function evaluations requiredTziter %d: ||F|| = %g, sigma = %gzsuccessful convergencer   r   )Úetar   )Úshapezdf-sane)r   ÚsuccessÚmessageÚfunÚnfevÚnitÚmethod)r   Ú
ValueErrorÚ
_wrap_funcÚcollectionsÚdequeÚprintÚabsr    Úsignr   r   r   ÚvdotÚappendÚ_wrap_resultr   )*ÚfuncÚx0ÚargsÚftolÚfatolÚmaxfevr   ÚcallbackÚdispÚMr   Ú	sigma_epsÚsigma_0Úline_searchÚunknown_optionsr#   r)   ÚfÚx_kÚx_shapeÚF_kÚ
is_complexr   Úsigma_kÚF_0_normÚprev_fsÚQÚCÚ	convergedr'   ÚF_k_normÚdr$   ÚalphaÚxpÚfpÚFpÚs_kÚy_kr   r   Úresultr   )r   r   r   r   Ú_root_df_sane   sˆ   1ÿ


ÿ
ÿ€ÿ
Î4
þrW   c           	         s¤   t  |¡}|j‰t  ˆ|gˆ ¢R Ž ¡ ¡ }t  |¡pt  |¡}| ¡ }dˆd< |r=‡ ‡‡‡‡‡fdd„}t|ƒ}t|ƒ}n‡ ‡‡‡‡‡fdd„}||ˆˆ|ƒ||fS )a¬  
    Wrap a function and an initial value so that (i) complex values
    are wrapped to reals, and (ii) value for a merit function
    fmerit(x, f) is computed at the same time, (iii) iteration count
    is maintained and an exception is raised if it is exceeded.

    Parameters
    ----------
    func : callable
        Function to wrap
    x0 : ndarray
        Initial value
    fmerit : callable
        Merit function fmerit(f) for computing merit value from residual.
    nfev_list : list
        List to store number of evaluations in. Should be [0] in the beginning.
    maxfev : int
        Maximum number of evaluations before _NoConvergence is raised.
    args : tuple
        Extra arguments to func

    Returns
    -------
    wrap_func : callable
        Wrapped function, to be called as
        ``F, fp = wrap_func(x0)``
    x0_wrap : ndarray of float
        Wrapped initial value; raveled to 1-D and complex
        values mapped to reals.
    x0_shape : tuple
        Shape of the initial value array
    f : float
        Merit function at F
    F : ndarray of float
        Residual at x0_wrap
    is_complex : bool
        Whether complex values were mapped to reals

    r   r   c                    sb   ˆd ˆkr	t ƒ ‚ˆd  d7  < t| ƒ ˆ¡}t ˆ|gˆ ¢R Ž ¡ ¡ }t|ƒ}ˆ|ƒ}||fS ©Nr   r   )r   Ú_real2complexÚreshaper    ÚasarrayÚravelÚ_complex2real)r   ÚzÚvr   rC   ©r8   r#   r6   r;   Ú	nfev_listÚx0_shaper   r   Ú	wrap_funcÙ   s   z_wrap_func.<locals>.wrap_funcc                    sV   ˆd ˆkr	t ƒ ‚ˆd  d7  < |  ˆ¡} t ˆ| gˆ ¢R Ž ¡ ¡ }ˆ|ƒ}||fS rX   )r   rZ   r    r[   r\   )r   r   rC   r`   r   r   rc   æ   s   
)r    r[   r%   r\   Úiscomplexobjr]   )	r6   r7   r#   ra   r;   r8   r   rG   rc   r   r`   r   r-   ¨   s   
(

	r-   c                 C   s(   |rt | ƒ}n| }|dur| |¡}|S )zA
    Convert from real to complex and reshape result arrays.
    N)rY   rZ   )rV   rG   r%   r^   r   r   r   r5   ò   s   

r5   c                 C   ó   t j| td� t j¡S ©N)Údtype)r    ÚascontiguousarrayÚfloatÚviewÚ
complex128)r   r   r   r   rY   ÿ   ó   rY   c                 C   re   rf   )r    rh   Úcomplexrj   Úfloat64)r^   r   r   r   r]     rl   r]   )r   r   r   r   NNFr   Nr   r   r   )r   r   )Ú__doc__r.   Únumpyr    Úscipy.optimizer   Úscipy.optimize._optimizer   Ú_linesearchr   r   Ú	Exceptionr   rW   r-   r5   rY   r]   r   r   r   r   Ú<module>   s     
þ 

J