
    (phO                     T   S r SSKJr  SSKrSSKJr  SSKJrJ	r	J
r
  SSKJr  SSKJrJr  \R                   " \5      R$                  rS r  S"S	 jrS
 rS rS#S jrS$S jrS%S jrS rS rS&S jrS&S jrS rS r S r!S r"S r#S r$S r%S%S jr&S r'S r(S r)S'S jr*S'S jr+S  r,S! r-g)(z+Functions used by least-squares algorithms.    )copysignN)norm)
cho_factor	cho_solveLinAlgError)issparse)LinearOperatoraslinearoperatorc                 T   [         R                  " X5      nUS:X  a  [        S5      e[         R                  " X5      n[         R                  " X 5      US-  -
  nUS:  a  [        S5      e[         R                  " XD-  X5-  -
  5      nU[	        Xd5      -   * nXs-  nXW-  n	X:  a  X4$ X4$ )aE  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
             M/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_lsq/common.pyintersect_trust_regionr      s      	qAAv((
qA
quaxA1u>??
ac	A hqn
A	
B	
B	wvv    c	                    S n	X2-  n
X:  a  [         U-  US   -  nUS   U:  nOSnU(       a(  UR                  X#-  5      * n[        U5      U::  a  USS4$ [        U
5      U-  nU(       a  U	" SXU5      u  nnU* U-  nOSnUb  U(       d  US:X  a  [        SU-  UU-  S-  5      nOUn[	        U5       Hx  nUU:  d  UU:  a  [        SU-  UU-  S-  5      nU	" UXU5      u  nnUS:  a  UnUU-  n[        UUU-
  5      nUX-   U-  U-  -  n[
        R                  " U5      Xu-  :  d  Mx    O   UR                  XS-  U-   -  5      * nX[        U5      -  -  nUUWS	-   4$ )
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                     US-  U -   n[        X-  5      nXS-
  n[        R                  " US-  US-  -  5      * U-  nXg4$ )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_derivative2solve_lsq_trust_region.<locals>.phi_and_derivativej   sO     1uck"nVVC1Huax/0069	~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
 &C 	v!GadN	bEI%		UU26]N7ec19s)e#K+C?YdY&I-12DEK'+*Cc)IJHo;%+"5+kK.G#-MNE+E35AY7Ki+uu}5#+&..66#;%   
sdUl#	$$A
 aAeR!Vr   c                 *    [        U 5      u  p4[        X44U5      * n[        R                  " XU5      US-  ::  a  US4$  U S   US-  -  nU S   US-  -  nU S   US-  -  nUS   U-  n	US   U-  n
[        R
                  " U* U	-   SXh-
  U
-   -  SU-  SU* U-   U
-   -  U* U	-
  /5      n[        R                  " U5      n[        R                  " U[        R                  " U5         5      nU[        R                  " SU-  SUS-  -   -  SUS-  -
  SUS-  -   -  45      -  nS	[        R                  " XPR                  U5      -  SS
9-  [        R                  " X5      -   n[        R                  " U5      nUSS2U4   nUS4$ ! [         a     GNRf = f)a2  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lowerr:   r   r   r   r   fcoeffstvalueis                  r   solve_trust_region_2drS      s   .a=z1%%66!<5!8#d7N $
 	
$%(A	$%(A	$%(A	!uA	!uAXX
aaeai!a%qb1fqj)9A26BDF
A
"))A, A		1q5A1H-AqDQAX/FGHHA"&&UU1XA..=E
		%A	!Q$Ae8O)  s   ;F 
FFc                     US:  a  X-  nOX!s=:X  a  S:X  a  O  OSnOSnUS:  a  SU-  n X4$ US:  a  U(       a  U S-  n X4$ )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_radiusr[      s`     Q 6		5A	5t|y  < 
)<r   c                    U R                  U5      n[        R                   " XU5      nUb  U[        R                   " X#-  U5      -  nUS-  n[        R                   " X5      nUb  U R                  U5      nU[        R                   " X5      -  nS[        R                   " X5      -  [        R                   " X5      -   n	Ub;  U[        R                   " XC-  U5      -  nU	S[        R                   " XC-  U5      -  -  n	XgU	4$ Xg4$ )aI  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   )
JrK   r   diags0vr   r   ur   s
             r   build_quadratic_1drb      s    > 	
aA
qA	RVVAHa  HA
qA	~EE"I	RVVA\"&&,.	1%%Arvvbi,,,AQwtr   c                     X#/nU S:w  a(  SU-  U -  nX&s=:  a  U:  a  O  OUR                  U5        [        R                  " U5      nXPU-  U-   -  U-   n[        R                  " U5      nXX   Xx   4$ )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   asarrayrI   )	r   r   lbubr   rP   extremumy	min_indexs	            r   minimize_quadratic_1drk   .  ss     
AAv!8a<2HHX


1A	UQY!A		!I<%%r   c                    UR                   S:X  aG  U R                  U5      n[        R                  " XD5      nUb  U[        R                  " X#-  U5      -  nOSU R                  UR                  5      n[        R                  " US-  SS9nUb  U[        R                  " X2S-  -  SS9-  n[        R                  " X!5      nSU-  U-   $ )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   rB   r+   )ndimr   r   Tr!   )r]   rK   r   r^   Jsr   ls          r   evaluate_quadraticrq   E  s    . 	vv{UU1XFF2N!$$AUU133ZFF2q5q!!t!,,A
qA7Q;r   c                 <    [         R                  " X:  X:*  -  5      $ )z$Check if a point lies within bounds.)r   all)r   rf   rg   s      r   	in_boundsrt   o  s    6617qw'((r   c                    [         R                  " U5      nX   n[         R                  " U 5      nUR                  [         R                  5        [         R
                  " SS9   [         R                  " X -
  U   U-  X0-
  U   U-  5      Xd'   SSS5        [         R                  " U5      nU[         R                  " Xg5      [         R                  " U5      R                  [        5      -  4$ ! , (       d  f       Nf= f)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   rf   rg   non_zero
s_non_zerostepsmin_steps           r   step_size_to_boundr   t  s    $ zz!}HJMM!E	JJrvv	(	#**bfh%7*%D&(fh%7*%DF 
$ vve}HRXXe.1B1B31GGGG	 
$	#s   $*C..
C<c                    [         R                  " U [        S9nUS:X  a  SX@U:*  '   SX@U:  '   U$ X-
  nX -
  nU[         R                  " S[         R                  " U5      5      -  nU[         R                  " S[         R                  " U5      5      -  n[         R
                  " U5      U[         R                  " Xg5      :*  -  n	SXI'   [         R
                  " U5      U[         R                  " XX5      :*  -  n
SXJ'   U$ )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}   r0   isfiniteminimum)r   rf   rg   r6   active
lower_dist
upper_distlower_thresholdupper_thresholdlower_activeupper_actives              r   find_active_constraintsr     s     ]]1C(FqyBwBwJ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           	      &   U R                  5       n[        XX#5      n[        R                  " US5      n[        R                  " US5      nUS:X  a;  [        R                  " X   X&   5      XF'   [        R                  " X'   X   5      XG'   OnX   U[        R
                  " S[        R                  " X   5      5      -  -   XF'   X'   U[        R
                  " S[        R                  " X'   5      5      -  -
  XG'   XA:  XB:  -  nSX   X(   -   -  XH'   U$ )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}   r0   )	r   rf   rg   rstepx_newr   
lower_mask
upper_masktight_boundss	            r   make_strictly_feasibler     s     FFHE$QB6F&"%J&!$JzLLHLLH^"RZZ266".3I%JJK^"RZZ266".3I%JJK J5:.L!1B4D!DEELr   c                    [         R                  " U 5      n[         R                  " U 5      nUS:  [         R                  " U5      -  nX6   X   -
  XF'   SXV'   US:  [         R                  " U5      -  nX   X&   -
  XF'   SXV'   XE4$ )a  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   rK   rf   rg   r`   dvmasks          r   CL_scaling_vectorr     s    < 	QA	q	BER[[_$Dh AGBHER[[_$Dg AGBH5Lr   c                    [        XU5      (       a  U [        R                  " U 5      4$ [        R                  " U5      n[        R                  " U5      nU R	                  5       n[        R
                  " U [        S9nX4) -  n[        R                  " X   SX   -  X   -
  5      XW'   X   X   :  Xg'   U) U-  n[        R                  " X   SX'   -  X   -
  5      XW'   X   X'   :  Xg'   X4-  nX!-
  n[        R                  " X   X   -
  SX   -  5      n	X   [        R                  " U	SX   -  U	-
  5      -   XW'   XU   :  Xg'   [        R                  " U 5      n
SX'   XZ4$ )z3Compute reflective transformation and its gradient.r   r   r*   )
rt   r   r   r   r   r   boolr}   r   	remainder)ri   rf   rg   	lb_finite	ub_finiter   
g_negativer   r   rP   rK   s              r   reflective_transformationr     sK   ",,q/!!BIBI	Aq-Jz!Djj!bh,"89AGw)J:	!Djj!bh,"89AGw)J D
A
QWrx'QW5AhAq17{Q77AGT7{J
QAAM4Kr   c            
      B    [        SR                  SSSSSS5      5        g )Nz${:^15}{:^15}{:^15}{:^15}{:^15}{:^15}	Iterationz
Total nfevCostCost reduction	Step norm
OptimalityprintformatrV   r   r   print_header_nonlinearr   !  s%    	
06+|V5E|-.r   c           	      b    Uc  SnOUS nUc  SnOUS n[        U S US US U U US 35        g Nz               z^15.2ez^15z^15.4er   )	iterationnfevcostcost_reductionrY   
optimalitys         r   print_iteration_nonlinearr   '  sX    !*62	 (		YsOD:d6]>2B9+jY_M`
abr   c            	      @    [        SR                  SSSSS5      5        g )Nz{:^15}{:^15}{:^15}{:^15}{:^15}r   r   r   r   r   r   rV   r   r   print_header_linearr   6  s#    	
*6+v'7 !r   c                 \    Uc  SnOUS nUc  SnOUS n[        U S US U U US 35        g r   r   )r   r   r   rY   r   s        r   print_iteration_linearr   <  sQ    !*62	 (		YsOD=(8JvCV
WXr   c                     [        U [        5      (       a  U R                  U5      $ U R                  R	                  U5      $ )z4Compute gradient of the least-squares cost function.)
isinstancer	   rmatvecrn   r   )r]   rN   s     r   compute_gradr   N  s/    !^$$yy|sswwqzr   c                 0   [        U 5      (       aD  [        R                  " U R                  S5      R	                  SS95      R                  5       S-  nO[        R                  " U S-  SS9S-  nUc  SX"S:H  '   O[        R                  " X!5      nSU-  U4$ )z5Compute variables scale based on the Jacobian matrix.r   r   rB   r+   r,   )r   r   re   powerr!   ravelr}   )r]   scale_inv_old	scale_invs      r   compute_jac_scaler   V  s    {{JJqwwqz~~1~56<<>C	FF1a4a(#-	$%	q.!JJy8	y=)##r   c                 p   ^ ^ [        T 5      m U U4S jnU U4S jnU U4S jn[        T R                  X#US9$ )z#Return diag(d) J as LinearOperator.c                 ,   > TTR                  U 5      -  $ N)matvecr   r]   r   s    r   r   (left_multiplied_operator.<locals>.matveci  s    188A;r   c                 V   > TS S 2[         R                  4   TR                  U 5      -  $ r   )r   newaxismatmatXr]   r   s    r   r   (left_multiplied_operator.<locals>.matmatl  s#    BJJ!((1+--r   c                 H   > TR                  U R                  5       T-  5      $ r   )r   r   r   s    r   r   )left_multiplied_operator.<locals>.rmatveco  s    yyQ''r   r   r   r   r
   r	   shaper]   r   r   r   r   s   ``   r   left_multiplied_operatorr   e  s6    A.( !''&")+ +r   c                 p   ^ ^ [        T 5      m U U4S jnU U4S jnU U4S jn[        T R                  X#US9$ )z#Return J diag(d) as LinearOperator.c                 T   > TR                  [        R                  " U 5      T-  5      $ r   )r   r   r   r   s    r   r   )right_multiplied_operator.<locals>.matvecz  s    xxa((r   c                 V   > TR                  U TS S 2[        R                  4   -  5      $ r   )r   r   r   r   s    r   r   )right_multiplied_operator.<locals>.matmat}  s$    xxAam,,--r   c                 ,   > TTR                  U 5      -  $ r   r   r   s    r   r   *right_multiplied_operator.<locals>.rmatvec  s    199Q<r   r   r   r   s   ``   r   right_multiplied_operatorr   v  s6    A).  !''&")+ +r   c                 x   ^ ^^ [        T 5      m T R                  u  mnU U4S jnU UU4S jn[        TU-   U4X4S9$ )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                 X   > [         R                  " TR                  U 5      TU -  45      $ r   )r   hstackr   )r   r]   r^   s    r   r   (regularized_lsq_operator.<locals>.matvec  s#    yy!((1+tax011r   c                 F   > U S T nU TS  nTR                  U5      TU-  -   $ r   r   )r   x1x2r]   r^   r2   s      r   r   )regularized_lsq_operator.<locals>.rmatvec  s0    rUqrUyy}tby((r   )r   r   )r
   r   r	   )r]   r^   r1   r   r   r2   s   ``   @r   regularized_lsq_operatorr     s=     	A77DAq2)
 1q5!*VEEr   c                 (   U(       a%  [        U [        5      (       d  U R                  5       n [        U 5      (       a/  U =R                  UR                  U R                  SS9-  sl        U $ [        U [        5      (       a  [        X5      n U $ X-  n U $ )z`Compute 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     s{    
 Jq.11FFH{{	!&&&00 H 
A~	&	&%a+ H 	
Hr   c                    U(       a%  [        U [        5      (       d  U R                  5       n [        U 5      (       aJ  U =R                  [
        R                  " U[
        R                  " U R                  5      5      -  sl        U $ [        U [        5      (       a  [        X5      n U $ XSS2[
        R                  4   -  n U $ )z`Compute 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1FFH{{	"))Arwwqxx011 H 
A~	&	&$Q* H 	
q"**}Hr   c                 z    XU-  :  =(       a    US:  nX&Xc-   -  :  nU(       a  U(       a  gU(       a  gU(       a  gg)z8Check termination condition for nonlinear least squares.rU      r   r    NrV   )	dFFdx_normx_normr>   ftolxtolftol_satisfiedxtol_satisfieds	            r   check_terminationr    s<    (]3ut|Nt}55N.		r   c                 ~    US   SUS   -  US-  -  -   n[         X3[         :  '   US-  nXS   U-  -  n[        XSS9U4$ )zXScale Jacobian and residuals for a robust loss function.

Arrays are modified in place.
r,   r   r+   F)r   )r-   r   )r]   rN   rhoJ_scales       r   scale_for_robust_loss_functionr    s[    
 !fq3q6zAqD((G GcMOGQ'	A%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?   rS   r[   rb   rk   rq   rt   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  rV   r   r   <module>r     s    1    ; ; ! @ 	hhuo$N AE/1od0f:0f&.$T)
H:$N6)XD.c!Y$$+"+"F,$$4r   