
    tKg+P                     B   d Z ddlmZ ddlZddlmZ ddlmZm	Z	m
Z
 ddlmZ ddlmZmZ  ej                   e      j$                  Zd Z	 	 d"d	Zd
 Zd Zd#dZd$dZd%dZd Zd Zd&dZd&dZd Zd Z d Z!d Z"d Z#d Z$d Z%d%dZ&d Z'd Z(d Z)d'dZ*d'dZ+d  Z,d! Z-y)(z+Functions used by least-squares algorithms.    )copysignN)norm)
cho_factor	cho_solveLinAlgError)issparse)LinearOperatoraslinearoperatorc                 \   t        j                  ||      }|dk(  rt        d      t        j                  | |      }t        j                  | |       |dz  z
  }|dkD  rt        d      t        j                  ||z  ||z  z
        }|t	        ||      z    }||z  }||z  }	||	k  r||	fS |	|fS )aq  Find the intersection of a line with the boundary of a trust region.

    This function solves the quadratic equation with respect to t
    ||(x + s*t)||**2 = Delta**2.

    Returns
    -------
    t_neg, t_pos : tuple of float
        Negative and positive roots.

    Raises
    ------
    ValueError
        If `s` is zero or `x` is not within the trust region.
    r   z`s` is zero.   z#`x` is not within the trust region.)npdot
ValueErrorsqrtr   )
xsDeltaabcdqt1t2s
             ^/home/alanp/www/video.onchill/myenv/lib/python3.12/site-packages/scipy/optimize/_lsq/common.pyintersect_trust_regionr      s      	q!AAv((
q!A
q!uaxA1u>??
!ac	A hq!n
A	
QB	
QB	Bw2v2v    c	                    d }	||z  }
|| k\  rt         |z  |d   z  }|d   |kD  }nd}|r(|j                  ||z         }t        |      |k  r|ddfS t        |
      |z  }|r |	d|
||      \  }}| |z  }nd}||s|dk(  rt        d|z  ||z  dz        }n|}t	        |      D ]u  }||k  s||kD  rt        d|z  ||z  dz        } |	||
||      \  }}|dk  r|}||z  }t        |||z
        }|||z   |z  |z  z  }t        j                  |      ||z  k  su n |j                  |
|dz  |z   z         }||t        |      z  z  }||d	z   fS )
a  Solve a trust-region problem arising in least-squares minimization.

    This function implements a method described by J. J. More [1]_ and used
    in MINPACK, but it relies on a single SVD of Jacobian instead of series
    of Cholesky decompositions. Before running this function, compute:
    ``U, s, VT = svd(J, full_matrices=False)``.

    Parameters
    ----------
    n : int
        Number of variables.
    m : int
        Number of residuals.
    uf : ndarray
        Computed as U.T.dot(f).
    s : ndarray
        Singular values of J.
    V : ndarray
        Transpose of VT.
    Delta : float
        Radius of a trust region.
    initial_alpha : float, optional
        Initial guess for alpha, which might be available from a previous
        iteration. If None, determined automatically.
    rtol : float, optional
        Stopping tolerance for the root-finding procedure. Namely, the
        solution ``p`` will satisfy ``abs(norm(p) - Delta) < rtol * Delta``.
    max_iter : int, optional
        Maximum allowed number of iterations for the root-finding procedure.

    Returns
    -------
    p : ndarray, shape (n,)
        Found solution of a trust-region problem.
    alpha : float
        Positive value such that (J.T*J + alpha*I)*p = -J.T*f.
        Sometimes called Levenberg-Marquardt parameter.
    n_iter : int
        Number of iterations made by root-finding procedure. Zero means
        that Gauss-Newton step was selected as the solution.

    References
    ----------
    .. [1] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation
           and Theory," Numerical Analysis, ed. G. A. Watson, Lecture Notes
           in Mathematics 630, Springer Verlag, pp. 105-116, 1977.
    c                     |dz  | z   }t        ||z        }||z
  }t        j                  |dz  |dz  z         |z  }||fS )zFunction of which to find zero.

        It is defined as "norm of regularized (by alpha) least-squares
        solution minus `Delta`". Refer to [1]_.
        r      )r   r   sum)alphasufr   r   denomp_normphi	phi_primes           r   phi_and_derivativez2solve_lsq_trust_region.<locals>.phi_and_derivativej   sU     1ucEk"unVVC1Huax/0069	I~r   r   Fg        gMbP?      ?r      )EPSr   r   maxranger   abs)nmufr   Vr   initial_alphartolmax_iterr(   r#   	threshold	full_rankpalpha_upperr&   r'   alpha_lowerr"   itratios                        r   solve_lsq_trust_regionr>   9   s   b
 b&C 	Av!GadN	bEI%		UU26]N7ec19s)e#K+Ca?YdY&I-12DEK'+*Cc)IJHo;%+"5+kK.G#-MNE+E35AY7Ki+uu}5#+&..66#;%   
sadUl#	$$A
 aAeR!Vr   c                 &   	 t        |       \  }}t        ||f|       }t        j                  ||      |dz  k  r|dfS 	 | d   |dz  z  }| d   |dz  z  }| d   |dz  z  }|d   |z  }	|d   |z  }
t        j
                  | |	z   d||z
  |
z   z  d|z  d| |z   |
z   z  | |	z
  g      }t        j                  |      }t        j                  |t        j                  |               }|t        j                  d|z  d|dz  z   z  d|dz  z
  d|dz  z   z  f      z  }d	t        j                  || j                  |      z  d
      z  t        j                  ||      z   }t        j                  |      }|dd|f   }|dfS # t        $ r Y Ow xY w)az  Solve a general trust-region problem in 2 dimensions.

    The problem is reformulated as a 4th order algebraic equation,
    the solution of which is found by numpy.roots.

    Parameters
    ----------
    B : ndarray, shape (2, 2)
        Symmetric matrix, defines a quadratic term of the function.
    g : ndarray, shape (2,)
        Defines a linear term of the function.
    Delta : float
        Radius of a trust region.

    Returns
    -------
    p : ndarray, shape (2,)
        Found solution.
    newton_step : bool
        Whether the returned solution is the Newton step which lies within
        the trust region.
    r   T)r   r   )r   r+   )r+   r+   r   r+      r*   axisNF)r   r   r   r   r   arrayrootsrealisrealvstackr!   argmin)Bgr   Rlowerr9   r   r   r   r   fcoeffstvalueis                  r   solve_trust_region_2drR      s   .a=55z1%%66!Q<5!8#d7N $
 	
$%(A	$%(A	$%(A	!uA	!uAXX
aa!eai!a%qb1fqj)9A26BDF
A
"))A, A		1q5A1H-AqDQAX/FGHHA"&&QUU1XA..1=E
		%A	!Q$Ae8O)  s   <F 	FFc                 z    |dkD  r||z  }n||cxk(  rdk(  rn nd}nd}|dk  r	d|z  } | |fS |dkD  r|r| dz  } | |fS )zUpdate the radius of a trust region based on the cost reduction.

    Returns
    -------
    Delta : float
        New radius.
    ratio : float
        Ratio between actual and predicted reductions.
    r   r+         ?g      ?g       @ )r   actual_reductionpredicted_reduction	step_norm	bound_hitr=   s         r   update_tr_radiusrZ      sj     Q #66	 0	5A	5t|y  %< 
)%<r   c                    | j                  |      }t        j                   ||      }||t        j                   ||z  |      z  }|dz  }t        j                   ||      }|| j                  |      }|t        j                   ||      z  }dt        j                   ||      z  t        j                   ||      z   }	|;|t        j                   ||z  |      z  }|	dt        j                   ||z  |      z  z  }	|||	fS ||fS )a  Parameterize a multivariate quadratic function along a line.

    The resulting univariate quadratic function is given as follows::

        f(t) = 0.5 * (s0 + s*t).T * (J.T*J + diag) * (s0 + s*t) +
               g.T * (s0 + s*t)

    Parameters
    ----------
    J : ndarray, sparse matrix or LinearOperator shape (m, n)
        Jacobian matrix, affects the quadratic term.
    g : ndarray, shape (n,)
        Gradient, defines the linear term.
    s : ndarray, shape (n,)
        Direction vector of a line.
    diag : None or ndarray with shape (n,), optional
        Addition diagonal part, affects the quadratic term.
        If None, assumed to be 0.
    s0 : None or ndarray with shape (n,), optional
        Initial point. If None, assumed to be 0.

    Returns
    -------
    a : float
        Coefficient for t**2.
    b : float
        Coefficient for t.
    c : float
        Free term. Returned only if `s0` is provided.
    r*   )r   r   )
JrJ   r   diags0vr   r   ur   s
             r   build_quadratic_1dra      s    > 	
aA
q!A	RVVAHa  HA
q!A	~EE"I	RVVAq\"&&A,2.T	1%%Arvvb4i,,,A!Qw!tr   c                     ||g}| dk7  r'd|z  | z  }||cxk  r|k  rn n|j                  |       t        j                  |      }|| |z  |z   z  |z   }t        j                  |      }||   ||   fS )zMinimize a 1-D quadratic function subject to bounds.

    The free term `c` is 0 by default. Bounds must be finite.

    Returns
    -------
    t : float
        Minimum point.
    y : float
        Minimum value.
    r   g      )appendr   asarrayrH   )	r   r   lbubr   rO   extremumy	min_indexs	            r   minimize_quadratic_1drj   .  s}     
RAAv!8a<2HHX


1A	QUQY!A		!IY<9%%r   c                    |j                   dk(  rF| j                  |      }t        j                  ||      }|t|t        j                  ||z  |      z  }nW| j                  |j                        }t        j                  |dz  d      }| |t        j                  ||dz  z  d      z  }t        j                  ||      }d|z  |z   S )a  Compute values of a quadratic function arising in least squares.

    The function is 0.5 * s.T * (J.T * J + diag) * s + g.T * s.

    Parameters
    ----------
    J : ndarray, sparse matrix or LinearOperator, shape (m, n)
        Jacobian matrix, affects the quadratic term.
    g : ndarray, shape (n,)
        Gradient, defines the linear term.
    s : ndarray, shape (k, n) or (n,)
        Array containing steps as rows.
    diag : ndarray, shape (n,), optional
        Addition diagonal part, affects the quadratic term.
        If None, assumed to be 0.

    Returns
    -------
    values : ndarray with shape (k,) or float
        Values of the function. If `s` was 2-D, then ndarray is
        returned, otherwise, float is returned.
    r+   r   r   rA   r*   )ndimr   r   Tr!   )r\   rJ   r   r]   Jsr   ls          r   evaluate_quadraticrp   E  s    . 	vv{UU1XFF2rND!$$AUU133ZFF2q5q!q!t!,,A
q!A7Q;r   c                 >    t        j                  | |k\  | |k  z        S )z$Check if a point lies within bounds.)r   all)r   re   rf   s      r   	in_boundsrs   o  s    6617qBw'((r   c                    t        j                  |      }||   }t        j                  |       }|j                  t         j                         t        j
                  d      5  t        j                  || z
  |   |z  || z
  |   |z        ||<   ddd       t        j                  |      }|t        j                  ||      t        j                  |      j                  t              z  fS # 1 sw Y   _xY w)a  Compute a min_step size required to reach a bound.

    The function computes a positive scalar t, such that x + s * t is on
    the bound.

    Returns
    -------
    step : float
        Computed step. Non-negative value.
    hits : ndarray of int with shape of x
        Each element indicates whether a corresponding variable reaches the
        bound:

             *  0 - the bound was not hit.
             * -1 - the lower bound was hit.
             *  1 - the upper bound was hit.
    ignore)overN)r   nonzero
empty_likefillinferrstatemaximumminequalsignastypeint)r   r   re   rf   non_zero
s_non_zerostepsmin_steps           r   step_size_to_boundr   t  s    $ zz!}H8JMM!E	JJrvv	(	#**b1fh%7*%D&(1fh%7*%DFh 
$ vve}HRXXeX.1B1B31GGGG	 
$	#s   %,C//C8c                    t        j                  | t              }|dk(  rd|| |k  <   d|| |k\  <   |S | |z
  }|| z
  }|t        j                  dt        j                  |            z  }|t        j                  dt        j                  |            z  }t        j
                  |      |t        j                  ||      k  z  }	d||	<   t        j
                  |      |t        j                  ||      k  z  }
d||
<   |S )a  Determine which constraints are active in a given point.

    The threshold is computed using `rtol` and the absolute value of the
    closest bound.

    Returns
    -------
    active : ndarray of int with shape of x
        Each component shows whether the corresponding constraint is active:

             *  0 - a constraint is not active.
             * -1 - a lower bound is active.
             *  1 - a upper bound is active.
    dtyper   r)   r+   )r   
zeros_liker   r|   r/   isfiniteminimum)r   re   rf   r5   active
lower_dist
upper_distlower_thresholdupper_thresholdlower_activeupper_actives              r   find_active_constraintsr     s     ]]1C(FqyqBwqBwRJaJRZZ266":66ORZZ266":66OKKO2::j/#JJLLF<KKO2::j/#JJLLF<Mr   c           	      :   | j                         }t        | |||      }t        j                  |d      }t        j                  |d      }|dk(  r?t        j                  ||   ||         ||<   t        j                  ||   ||         ||<   np||   |t        j
                  dt        j                  ||               z  z   ||<   ||   |t        j
                  dt        j                  ||               z  z
  ||<   ||k  ||kD  z  }d||   ||   z   z  ||<   |S )zShift a point to the interior of a feasible region.

    Each element of the returned vector is at least at a relative distance
    `rstep` from the closest bound. If ``rstep=0`` then `np.nextafter` is used.
    r)   r+   r   r*   )copyr   r   r~   	nextafterr|   r/   )	r   re   rf   rstepx_newr   
lower_mask
upper_masktight_boundss	            r   make_strictly_feasibler     s    FFHE$QB6F&"%J&!$JzLLJJHjLLJJHj
^"RZZ266"Z.3I%JJKj
^"RZZ266"Z.3I%JJKj BJ52:.LL!1B|4D!DEE,Lr   c                    t        j                  |       }t        j                  |       }|dk  t        j                  |      z  }||   | |   z
  ||<   d||<   |dkD  t        j                  |      z  }| |   ||   z
  ||<   d||<   ||fS )a4  Compute Coleman-Li scaling vector and its derivatives.

    Components of a vector v are defined as follows::

               | ub[i] - x[i], if g[i] < 0 and ub[i] < np.inf
        v[i] = | x[i] - lb[i], if g[i] > 0 and lb[i] > -np.inf
               | 1,           otherwise

    According to this definition v[i] >= 0 for all i. It differs from the
    definition in paper [1]_ (eq. (2.2)), where the absolute value of v is
    used. Both definitions are equivalent down the line.
    Derivatives of v with respect to x take value 1, -1 or 0 depending on a
    case.

    Returns
    -------
    v : ndarray with shape of x
        Scaling vector.
    dv : ndarray with shape of x
        Derivatives of v[i] with respect to x[i], diagonal elements of v's
        Jacobian.

    References
    ----------
    .. [1] M.A. Branch, T.F. Coleman, and Y. Li, "A Subspace, Interior,
           and Conjugate Gradient Method for Large-Scale Bound-Constrained
           Minimization Problems," SIAM Journal on Scientific Computing,
           Vol. 21, Number 1, pp 1-23, 1999.
    r   r)   r+   )r   	ones_liker   r   )r   rJ   re   rf   r_   dvmasks          r   CL_scaling_vectorr     s    < 	QA	q	BER[[_$Dh4 AdGBtHER[[_$Dg4 AdGBtHb5Lr   c                    t        | ||      r| t        j                  |       fS t        j                  |      }t        j                  |      }| j	                         }t        j
                  | t              }|| z  }t        j                  | |   d||   z  | |   z
        ||<   | |   ||   k  ||<   | |z  }t        j                  | |   d||   z  | |   z
        ||<   | |   ||   kD  ||<   ||z  }||z
  }t        j                  | |   ||   z
  d||   z        }	||   t        j                  |	d||   z  |	z
        z   ||<   |	||   kD  ||<   t        j                  |       }
d|
|<   ||
fS )z3Compute reflective transformation and its gradient.r   r   r)   )
rs   r   r   r   r   r   boolr|   r   	remainder)rh   re   rf   	lb_finite	ub_finiter   
g_negativer   r   rO   rJ   s              r   reflective_transformationr     s   B",,q/!!BIBI	Aq-J	z!Djj4!bh,4"89AdGwD)Jt:	!Djj4!bh,4"89AdGwD)Jty D
RA
QtWr$x'QtW5AhAq1T7{Q77AdG1T7{Jt
QAAjMa4Kr   c            
      B    t        dj                  dddddd             y )Nz${:^15}{:^15}{:^15}{:^15}{:^15}{:^15}	Iterationz
Total nfevCostCost reduction	Step norm
OptimalityprintformatrU   r   r   print_header_nonlinearr   !  s%    	
06+|V5E|-.r   c           
      f    |d}n|d}|d}n|d}t        dj                  | |||||             y )N               ^15.2ez"{:^15}{:^15}{:^15.4e}{}{}{:^15.2e}r   )	iterationnfevcostcost_reductionrX   
optimalitys         r   print_iteration_nonlinearr   '  sN    !*62	 (		
.6)T4Z)*r   c            	      @    t        dj                  ddddd             y )Nz{:^15}{:^15}{:^15}{:^15}{:^15}r   r   r   r   r   r   rU   r   r   print_header_linearr   8  s#    	
*6+v'7 !r   c                 X    |d}n|d}|d}n|d}t        | d|d| | |d       y )Nr   r   z^15z^15.4e)r   )r   r   r   rX   r   s        r   print_iteration_linearr   >  sQ    !*62	 (		YsOD=(8JvCV
WXr   c                 z    t        | t              r| j                  |      S | j                  j	                  |      S )z4Compute gradient of the least-squares cost function.)
isinstancer	   rmatvecrm   r   )r\   rM   s     r   compute_gradr   P  s,    !^$yy|sswwqzr   c                 .   t        |       rFt        j                  | j                  d      j	                  d            j                         dz  }nt        j                  | dz  d      dz  }|	d||dk(  <   nt        j                  ||      }d|z  |fS )z5Compute variables scale based on the Jacobian matrix.r   r   rA   r*   r+   )r   r   rd   powerr!   ravelr|   )r\   scale_inv_old	scale_invs      r   compute_jac_scaler   X  s    {JJqwwqz~~1~56<<>C	FF1a4a(#-	$%	)q.!JJy-8	y=)##r   c                 r     t                 fd} fd} fd}t         j                  |||      S )z#Return diag(d) J as LinearOperator.c                 ,    j                  |       z  S N)matvecr   r\   r   s    r   r   z(left_multiplied_operator.<locals>.matveck  s    188A;r   c                 V    d d t         j                  f   j                  |       z  S r   )r   newaxismatmatXr\   r   s    r   r   z(left_multiplied_operator.<locals>.matmatn  s#    BJJ!((1+--r   c                 H    j                  | j                         z        S r   )r   r   r   s    r   r   z)left_multiplied_operator.<locals>.rmatvecq  s    yyQ''r   r   r   r   r
   r	   shaper\   r   r   r   r   s   ``   r   left_multiplied_operatorr   g  s8    A.( !''&")+ +r   c                 r     t                 fd} fd} fd}t         j                  |||      S )z#Return J diag(d) as LinearOperator.c                 R    j                  t        j                  |       z        S r   )r   r   r   r   s    r   r   z)right_multiplied_operator.<locals>.matvec|  s    xxa((r   c                 V    j                  | d d t        j                  f   z        S r   )r   r   r   r   s    r   r   z)right_multiplied_operator.<locals>.matmat  s$    xxAam,,--r   c                 ,    j                  |       z  S r   r   r   s    r   r   z*right_multiplied_operator.<locals>.rmatvec  s    199Q<r   r   r   r   s   ``   r   right_multiplied_operatorr   x  s8    A).  !''&")+ +r   c                 |     t                 j                  \  } fd} fd}t        |z   |f||      S )zReturn a matrix arising in regularized least squares as LinearOperator.

    The matrix is
        [ J ]
        [ D ]
    where D is diagonal matrix with elements from `diag`.
    c                 V    t        j                  j                  |       | z  f      S r   )r   hstackr   )r   r\   r]   s    r   r   z(regularized_lsq_operator.<locals>.matvec  s#    yy!((1+tax011r   c                 F    | d  }| d  }j                  |      |z  z   S r   r   )r   x1x2r\   r]   r1   s      r   r   z)regularized_lsq_operator.<locals>.rmatvec  s0    rUqrUyy}tby((r   )r   r   )r
   r   r	   )r\   r]   r0   r   r   r1   s   ``   @r   regularized_lsq_operatorr     s?     	A77DAq2)
 1q5!*VWEEr   c                 
   |r t        | t              s| j                         } t        |       r2| xj                  |j                  | j                  d      z  c_        | S t        | t              rt        | |      } | S | |z  } | S )zhCompute J diag(d).

    If `copy` is False, `J` is modified in place (unless being LinearOperator).
    clip)mode)r   r	   r   r   datatakeindicesr   r\   r   r   s      r   right_multiplyr     sw    
 Jq.1FFH{	!&&&00 H 
A~	&%a+ H 	
QHr   c                 `   |r t        | t              s| j                         } t        |       rH| xj                  t        j                  |t        j                  | j                              z  c_        | S t        | t              rt        | |      } | S | |ddt
        j                  f   z  } | S )zhCompute diag(d) J.

    If `copy` is False, `J` is modified in place (unless being LinearOperator).
    N)r   r	   r   r   r   r   repeatdiffindptrr   r   r   s      r   left_multiplyr     s    
 Jq.1FFH{	"))Arwwqxx011 H 
A~	&$Q* H 	
Qq"**}Hr   c                 N    | ||z  k  xr |dkD  }||||z   z  k  }|r|ry|ry|ryy)z8Check termination condition for nonlinear least squares.rT      r   r    NrU   )	dFFdx_normx_normr=   ftolxtolftol_satisfiedxtol_satisfieds	            r   check_terminationr     sB    $(]3ut|Nttf}55N.		r   c                     |d   d|d   z  |dz  z  z   }t         ||t         k  <   |dz  }||d   |z  z  }t        | |d      |fS )z`Scale Jacobian and residuals for a robust loss function.

    Arrays are modified in place.
    r+   r   r*   F)r   )r,   r   )r\   rM   rhoJ_scales       r   scale_for_robust_loss_functionr    sa    
 !fq3q6zAqD((G GGcMOGQ'	AG%0!33r   )Ng{Gz?
   )NN)r   r   )g|=)T).__doc__mathr   numpyr   numpy.linalgr   scipy.linalgr   r   r   scipy.sparser   scipy.sparse.linalgr	   r
   finfofloatepsr,   r   r>   rR   rZ   ra   rj   rp   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  rU   r   r   <module>r     s    1    ; ; ! @ bhhuo$N AE/1od0f:0f&.$T)
H:$N6)XD.*"!Y$$+"+"F,$$4r   