
    tKg1*                         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 Z G d d	      Z	 	 	 	 	 dd
Zy)zTrust-region optimization.    N   )_check_unknown_options_status_messageOptimizeResult_prepare_scalar_function_call_callback_maybe_halt)HessianUpdateStrategy)
FD_METHODSc                 0     dg d fS  fd}|fS )Nr   c                 \    dxx   dz  cc<    t        j                  |       g|z    S )Nr   r   )npcopy)xwrapper_argsargsfunctionncallss     _/home/alanp/www/video.onchill/myenv/lib/python3.12/site-packages/scipy/optimize/_trustregion.pyfunction_wrapperz(_wrap_function.<locals>.function_wrapper   s-    q	Q	
;lT&9;;     )r   r   r   r   s   `` @r   _wrap_functionr      s/     SFt|<
 ###r   c                   p    e Zd ZdZddZd Zed        Zed        Zed        Z	d Z
ed	        Zd
 Zd Zy)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                     || _         d | _        d | _        d | _        d | _        d | _        d | _        || _        || _        || _	        || _
        y N)_x_f_g_h_g_mag_cauchy_point_newton_point_fun_jac_hess_hessp)selfr   funjachesshessps         r   __init__z BaseQuadraticSubproblem.__init__(   sQ    !!		
r   c                     | j                   t        j                  | j                  |      z   dt        j                  || j	                  |            z  z   S )Ng      ?)r)   r   dotr*   r,   r(   ps     r   __call__z BaseQuadraticSubproblem.__call__5   s=    xx"&&1--bffQ

16N0NNNr   c                 r    | j                    | j                  | j                        | _         | j                   S )z1Value of objective function at current iteration.)r   r$   r   r(   s    r   r)   zBaseQuadraticSubproblem.fun8   *     77?ii(DGwwr   c                 r    | j                    | j                  | j                        | _         | j                   S )z=Value of Jacobian of objective function at current iteration.)r   r%   r   r4   s    r   r*   zBaseQuadraticSubproblem.jac?   r5   r   c                 r    | j                    | j                  | j                        | _         | j                   S )z<Value of Hessian of objective function at current iteration.)r    r&   r   r4   s    r   r+   zBaseQuadraticSubproblem.hessF   s*     77?jj)DGwwr   c                     | j                   | j                  | j                  |      S t        j                  | j                  |      S r   )r'   r   r   r/   r+   r0   s     r   r,   zBaseQuadraticSubproblem.hesspM   s6    ;;";;tww**66$))Q''r   c                     | j                   .t        j                  j                  | j                        | _         | j                   S )zAMagnitude of jacobian of objective function at current iteration.)r!   scipylinalgnormr*   r4   s    r   jac_magzBaseQuadraticSubproblem.jac_magS   s2     ;;,,++DHH5DK{{r   c                 H   t        j                  ||      }dt        j                  ||      z  }t        j                  ||      |dz  z
  }t        j                  ||z  d|z  |z  z
        }|t        j                  ||      z   }| d|z  z  }	d|z  |z  }
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tbs              r   get_boundaries_intersectionsz4BaseQuadraticSubproblem.get_boundaries_intersectionsZ   s     FF1aLq!FF1aL<?* IIacAaCEk2 $-- 1155TQqS\TCZr2hr   c                     t        d      )Nz9The solve method should be implemented by the child class)NotImplementedError)r(   rH   s     r   solvezBaseQuadraticSubproblem.solveq   s    ! #4 5 	5r   )NN)__name__
__module____qualname____doc__r-   r2   propertyr)   r*   r+   r,   r=   rP   rS   r   r   r   r   r      sq    O      (   .5r   r   c                   # t        |       |t        d      ||t        d      |t        d      d|	cxk  rdk  st        d       t        d      |dk  rt        d      |dk  rt        d	      ||k\  rt        d
      t        j                  |      j                         }t        | ||||      ##j                  } #j                  }t        |      r#j                  }n7t        |      rn+|t        v st        |t              rd}#fd}nt        d      t        ||      \  }}|t        |      dz  }d}|}|}|r|g} ||| |||      }d}|j                   |
k\  r	 |j#                  |      \  }} ||      }||z   } ||| |||      }|j                  |j                  z
  }|j                  |z
  }|dk  rd}n||z  }|dk  r|dz  }n|dkD  r|rt)        d|z  |      }||	kD  r|}|}|r$j+                  t        j,                  |             |dz  }t/        ||j                        } t1        ||       rn+|j                   |
k  rd}n||k\  rd}n|j                   |
k\  rt2        d   t2        d   ddf}!|r|dk(  rt5        |!|          nt7        j8                  |!|   t:        d       t5        d|j                  z         t5        d|z         t5        d#j<                  z         t5        d#j>                  z         t5        d#j@                  |d   z   z         t/        ||dk(  ||j                  |jB                  #j<                  #j>                  #j@                  |d   z   ||!|   
      }"||j                  |"d<   |r|"d<   |"S # t        j$                  j&                  $ r d}Y Lw xY w) 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                 D    j                  |       j                  |      S r   )r+   r/   )r   r1   r   sfs      r   r,   z%_minimize_trust_region.<locals>.hessp   s    771:>>!$$r         r?   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   r^   statusr)   r*   nfevnjevnhevnitmessager+   allvecs)"r   
ValueError	Exceptionr   asarrayflattenr   r)   gradcallabler+   r
   
isinstancer	   r   lenr=   rS   r;   LinAlgErrorminappendr   r   r   r   printwarningswarnRuntimeWarningrb   ngevrd   r*   )$r)   x0r   r*   r+   r,   
subprobleminitial_trust_radiusmax_trust_radiusetagtolr_   disp
return_allcallbackinexactunknown_optionsnhesspwarnflagrH   r   rg   mkr1   hits_boundarypredicted_value
x_proposed
m_proposedactual_reductionpredicted_reductionrhointermediate_resultstatus_messagesresultr[   s$                                      @r   _minimize_trust_regionr   v   s2   > ?+
{ # $ 	$| J K 	K 0 1 	1OtO788 7881?@@q DEE// , - 	- 
B			!B 
"#rsD	IB
&&C
''C~ww	% 	
*

41F G 	%  J K 	K #5$/MFE b'#+ H (L
A#1c3e,A	A ))t
	 ww|4A} A$ U

CdEB
 55:>>1eeo5!#H!44 :D L4ZMq~/?@L 9AA NN2771:&	Q,qaee<$X/BC 99tH <Ho ))t
v I&I&HA	O q=/(+,MM/(3^PQR3aee;<'!+,1BGG;<1BGG;<0BGGfQi4GHIa(a- !155rwwRWW!#6!9!4!$3H$=?F
 v#yM] yy$$ 	H	s   +N N>=N>)r   NNNNg      ?g     @@g333333?g-C6?NFFNT)rW   rB   rt   numpyr   scipy.linalgr:   	_optimizer   r   r   r   r   'scipy.optimize._hessian_update_strategyr	   (scipy.optimize._differentiable_functionsr
   __all__r   r   r   r   r   r   <module>r      sW         3 3 J ?
$U5 U5p IMADCG@E26	zr   