o
    Ö­j1*  ã                   @   sŠ   d Z ddlZddlZddlZddlZddlmZm	Z	m
Z
mZmZ ddlmZ ddlmZ g Zdd„ ZG d	d
„ d
ƒZ					ddd„ZdS )zTrust-region optimization.é    Né   )Ú_check_unknown_optionsÚ_status_messageÚOptimizeResultÚ_prepare_scalar_functionÚ_call_callback_maybe_halt)ÚHessianUpdateStrategy)Ú
FD_METHODSc                    s.   dg‰ˆd u rˆd fS ‡ ‡‡fdd„}ˆ|fS )Nr   c                    s*   ˆd  d7  < ˆt  | ¡g|ˆ  ¢R Ž S )Nr   r   )ÚnpÚcopy)ÚxÚwrapper_args©ÚargsÚfunctionÚncalls© úX/var/www/html/CropPilot/venv/lib/python3.10/site-packages/scipy/optimize/_trustregion.pyÚfunction_wrapper   s   z(_wrap_function.<locals>.function_wrapperr   )r   r   r   r   r   r   Ú_wrap_function   s
   r   c                   @   sj   e Zd ZdZddd„Zdd„ Zedd„ ƒZed	d
„ ƒZedd„ ƒZ	dd„ Z
edd„ ƒZdd„ Zdd„ ZdS )ÚBaseQuadraticSubproblemaQ  
    Base/abstract class defining the quadratic model for trust-region
    minimization. Child classes must implement the ``solve`` method.

    Values of the objective function, Jacobian and Hessian (if provided) at
    the current iterate ``x`` are evaluated on demand and then stored as
    attributes ``fun``, ``jac``, ``hess``.
    Nc                 C   sF   || _ d | _d | _d | _d | _d | _d | _|| _|| _|| _	|| _
d S ©N)Ú_xÚ_fÚ_gÚ_hÚ_g_magÚ_cauchy_pointÚ_newton_pointÚ_funÚ_jacÚ_hessÚ_hessp)Úselfr   ÚfunÚjacÚhessÚhesspr   r   r   Ú__init__(   s   
z BaseQuadraticSubproblem.__init__c                 C   s*   | j t | j|¡ dt ||  |¡¡  S )Ng      à?)r$   r
   Údotr%   r'   ©r#   Úpr   r   r   Ú__call__5   s   *z BaseQuadraticSubproblem.__call__c                 C   ó   | j du r|  | j¡| _ | j S )z1Value of objective function at current iteration.N)r   r   r   ©r#   r   r   r   r$   8   ó   
zBaseQuadraticSubproblem.func                 C   r-   )z=Value of Jacobian of objective function at current iteration.N)r   r    r   r.   r   r   r   r%   ?   r/   zBaseQuadraticSubproblem.jacc                 C   r-   )z<Value of Hessian of objective function at current iteration.N)r   r!   r   r.   r   r   r   r&   F   r/   zBaseQuadraticSubproblem.hessc                 C   s&   | j d ur|   | j|¡S t | j|¡S r   )r"   r   r
   r)   r&   r*   r   r   r   r'   M   s   
zBaseQuadraticSubproblem.hesspc                 C   s    | j du rtj | j¡| _ | j S )zAMagnitude of jacobian of objective function at current iteration.N)r   ÚscipyÚlinalgÚnormr%   r.   r   r   r   Újac_magS   s   
zBaseQuadraticSubproblem.jac_magc                 C   s€   t  ||¡}dt  ||¡ }t  ||¡|d  }t || d| |  ¡}|t ||¡ }| d|  }	d| | }
t|	|
gƒS )zÄ
        Solve the scalar quadratic equation ``||z + t d|| == trust_radius``.
        This is like a line-sphere intersection.
        Return the two values of t, sorted from low to high.
        é   é   éþÿÿÿ)r
   r)   ÚmathÚsqrtÚcopysignÚsorted)r#   ÚzÚdÚtrust_radiusÚaÚbÚcÚsqrt_discriminantÚauxÚtaÚtbr   r   r   Úget_boundaries_intersectionsZ   s   	z4BaseQuadraticSubproblem.get_boundaries_intersectionsc                 C   s   t dƒ‚)Nz9The solve method should be implemented by the child class)ÚNotImplementedError)r#   r=   r   r   r   Úsolveq   s   zBaseQuadraticSubproblem.solve)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r(   r,   Úpropertyr$   r%   r&   r'   r3   rE   rG   r   r   r   r   r      s    
	



r   r   ç      ð?ç     @�@ç333333Ã?ç-Cëâ6?FTc           #         sr  t |ƒ |du rtdƒ‚|du r|du rtdƒ‚|du r tdƒ‚d|	  kr-dk s2tdƒ‚ tdƒ‚|dkr:tdƒ‚|dkrBtd	ƒ‚||krJtd
ƒ‚t |¡ ¡ }t| ||||d�‰ ˆ j} ˆ j}t	|ƒrhˆ j
}nt	|ƒrmn|tv svt|tƒrd}‡ fdd„}ntdƒ‚t||ƒ\}}|du r”t|ƒd }d}|}|}|rŸ|g}||| |||ƒ}d}|j|
k�r@z	| |¡\}}W n tjjyÅ   d}Y n{w ||ƒ}|| }||| |||ƒ}|j|j }|j| }|dkrèd}nX|| }|dk rõ|d9 }n|dk�r|�rtd| |ƒ}||	k�r|}|}|�r| t |¡¡ |d7 }t||jd�} t|| ƒ�r*n|j|
k �r3d}n||k�r;d}n|j|
ks¯td td ddf}!|�r‹|dk�rYt|!| ƒ n
tj|!| tdd� td|jd›�ƒ td| ƒ tdˆ j ƒ tdˆ j ƒ tdˆ j |d   ƒ t||dk||j|j!ˆ jˆ jˆ j |d  ||!| d�
}"|du�r°|j
|"d < |�r·||"d!< |"S )"aÐ  
    Minimization of scalar function of one or more variables using a
    trust-region algorithm.

    Options for the trust-region algorithm are:
        initial_trust_radius : float
            Initial trust radius.
        max_trust_radius : float
            Never propose steps that are longer than this value.
        eta : float
            Trust region related acceptance stringency for proposed steps.
        gtol : float
            Gradient norm must be less than `gtol`
            before successful termination.
        maxiter : int
            Maximum number of iterations to perform.
        disp : bool
            If True, print convergence message.
        inexact : bool
            Accuracy to solve subproblems. If True requires less nonlinear
            iterations, but more vector products. Only effective for method
            trust-krylov.

    This function is called by the `minimize` function.
    It is not supposed to be called directly.
    Nz7Jacobian is currently required for trust-region methodsz_Either the Hessian or the Hessian-vector product is currently required for trust-region methodszBA subproblem solving strategy is required for trust-region methodsr   g      Ð?zinvalid acceptance stringencyz%the max trust radius must be positivez)the initial trust radius must be positivez?the initial trust radius must be less than the max trust radius)r%   r&   r   c                    s   ˆ   | ¡ |¡S r   )r&   r)   )r   r+   r   ©Úsfr   r   r'   À   s   z%_minimize_trust_region.<locals>.hesspéÈ   é   r4   g      è?r   )r   r$   ÚsuccessÚmaxiterz:A bad approximation caused failure to predict improvement.z3A linalg error occurred, such as a non-psd Hessian.)Ú
stacklevelz!         Current function value: Úfz         Iterations: %dz!         Function evaluations: %dz!         Gradient evaluations: %dz          Hessian evaluations: %d)
r   rU   Ústatusr$   r%   ÚnfevÚnjevÚnhevÚnitÚmessager&   Úallvecs)"r   Ú
ValueErrorÚ	Exceptionr
   ÚasarrayÚflattenr   r$   ÚgradÚcallabler&   r	   Ú
isinstancer   r   Úlenr3   rG   r1   ÚLinAlgErrorÚminÚappendr   r   r   r   ÚprintÚwarningsÚwarnÚRuntimeWarningrZ   Úngevr\   r%   )#r$   Úx0r   r%   r&   r'   Ú
subproblemÚinitial_trust_radiusÚmax_trust_radiusÚetaÚgtolrV   ÚdispÚ
return_allÚcallbackÚinexactÚunknown_optionsÚnhesspÚwarnflagr=   r   r_   ÚmÚkr+   Úhits_boundaryÚpredicted_valueÚ
x_proposedÚ
m_proposedÚactual_reductionÚpredicted_reductionÚrhoÚintermediate_resultÚstatus_messagesÚresultr   rQ   r   Ú_minimize_trust_regionv   sÆ   ÿþ




É;ü
ý

r‰   )r   NNNNrM   rN   rO   rP   NFFNT)rK   r7   rl   Únumpyr
   Úscipy.linalgr0   Ú	_optimizer   r   r   r   r   Ú'scipy.optimize._hessian_update_strategyr   Ú(scipy.optimize._differentiable_functionsr	   Ú__all__r   r   r‰   r   r   r   r   Ú<module>   s"    Xü