
    ^MhO                     6   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-dS ),z+Functions used by least-squares algorithms.    )copysignN)norm)
cho_factor	cho_solveLinAlgError)issparse)LinearOperatoraslinearoperatorc                 r   t          j        ||          }|dk    rt          d          t          j        | |          }t          j        | |           |dz  z
  }|dk    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
             Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_lsq/common.pyintersect_trust_regionr      s      	q!AAvv(((
q!A
q!uaxA1uu>???
!ac	A hq!nn
A	
QB	
QB	Bww2v2v    {Gz?
   c	                    d }	||z  }
|| k    r t           |z  |d         z  }|d         |k    }nd}|r1|                    ||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 ]}||k     s||k    rt          d|z  ||z  dz            } |	||
||          \  }}|dk     r|}||z  }t          |||z
            }|||z   |z  |z  z  }t          j        |          ||z  k     r n|                    |
|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   sY     1ucEk""unVC1Huax/00069	I~r   r   Fg        NgMbP?      ?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 	Avv!GadN	bEI%			 UU26]]N77ec19s))e#K ++Ca??YdY&I-12D2DEK'+*Cc)IJJHoo  ;%+"5"5+kK.G#-MNNE++E35AAY77Ki+uu}55#+&..6#;;%%E & 
sadUl#	$	$$A
 aAeR!Vr   c                 X   	 t          |           \  }}t          ||f|           }t          j        ||          |dz  k    r|dfS n# t          $ r Y nw xY w| 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
        ||                     |          z  d
          z  t          j        ||          z   }t          j        |          }|dd|f         }|dfS )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lowerr;   r   r   r   r   fcoeffstvalueis                  r   solve_trust_region_2drT      s   .a==55z1%%%6!Q<<5!8##d7N $    	
$%(A	$%(A	$%(A	!uA	!uAX
aa!eai!a%qb1fqj)9A26BD DF
A
")A,,  A	1q5A1H-AqDQAX/FGHHHA"&QUU1XXA....1=E
	%A	!!!Q$Ae8Os   AA 
AAc                 ~    |dk    r||z  }n||cxk    rdk    rn nd}nd}|dk     rd|z  } n|dk    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_radiusr\      s     Q #66	 0	5	5	5	5A	5	5	5	5	5t||y 	)%<r   c                    |                      |          }t          j         ||          }||t          j         ||z  |          z  }|dz  }t          j         ||          }||                      |          }|t          j         ||          z  }dt          j         ||          z  t          j         ||          z   }	|9|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.
    Nr,   )r   r   )
JrL   r   diags0vr   r   ur   s
             r   build_quadratic_1drc      s    > 	
aA
q!A	RVAHa   HA
q!A	~EE"II	RVAq\\"&A,,2.T	1%%%Arvb4i,,,,A!Qw!tr   c                     ||g}| dk    r-d|z  | z  }||cxk     r|k     rn n|                     |           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   asarrayrJ   )	r   r   lbubr   rQ   extremumy	min_indexs	            r   minimize_quadratic_1drl   .  s     
RAAvv!8a<2HHX

1A	QUQY!A	!IY<9%%r   c                    |j         dk    rH|                     |          }t          j        ||          }||t          j        ||z  |          z  }nT|                     |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-   Nr   r   rC   r,   )ndimr   r   Tr#   )r^   rL   r   r_   Jsr   ls          r   evaluate_quadraticrr   E  s    . 	v{{UU1XXF2rNND!$$$AUU13ZZF2q5q!!!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   rg   rh   s      r   	in_boundsru   o  s    617qBw'(((r   c                 
   t          j        |          }||         }t          j        |           }|                    t           j                   t          j        d          5  t          j        || z
  |         |z  || z
  |         |z            ||<   ddd           n# 1 swxY w Y   t          j        |          }|t          j        ||          t          j	        |          
                    t                    z  fS )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   rg   rh   non_zero
s_non_zerostepsmin_steps           r   step_size_to_boundr   t  s/   $ z!}}H8JM!E	JJrv	(	#	#	# F F*b1fh%7*%D&(1fh%7*%DF FhF F F F F F F F F F F F F F F ve}}HRXeX..1B1B31G1GGGGs   %1B""B&)B&绽|=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~   r1   isfiniteminimum)r   rg   rh   r7   active
lower_dist
upper_distlower_thresholdupper_thresholdlower_activeupper_actives              r   find_active_constraintsr     s     ]1C(((FqyyqBwqBwRJaJRZ26"::666ORZ26"::666OKOO2:j/#J#JJLLF<KOO2:j/#J#JJLLF<Mr   c           	      |   |                                  }t          | |||          }t          j        |d          }t          j        |d          }|dk    rIt          j        ||         ||                   ||<   t          j        ||         ||                   ||<   nx||         |t          j        dt          j        ||                             z  z   ||<   ||         |t          j        dt          j        ||                             z  z
  ||<   ||k     ||k    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~   r1   )	r   rg   rh   rstepx_newr   
lower_mask
upper_masktight_boundss	            r   make_strictly_feasibler     s1    FFHHE$QB66F&"%%J&!$$JzzLJJHHjLJJHHj
^"RZ26"Z.3I3I%J%JJKj
^"RZ26"Z.3I3I%J%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k    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   rL   rg   rh   ra   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                 J   t          | ||          r| t          j        |           fS t          j        |          }t          j        |          }|                                 }t          j        | t                    }|| z  }t          j        | |         d||         z  | |         z
            ||<   | |         ||         k     ||<   | |z  }t          j        | |         d||         z  | |         z
            ||<   | |         ||         k    ||<   ||z  }||z
  }t          j	        | |         ||         z
  d||         z            }	||         t          j        |	d||         z  |	z
            z   ||<   |	||         k    ||<   t          j        |           }
d|
|<   ||
fS )z3Compute reflective transformation and its gradient.r   r   r+   )
ru   r   r   r   r   r   boolr~   r   	remainder)rj   rg   rh   	lb_finite	ub_finiter   
g_negativer   r   rQ   rL   s              r   reflective_transformationr     s   B "",q//!!BIBI	Aq---J	z!Dj4!bh,4"899AdGwD)Jt:	!Dj4!bh,4"899AdGwD)Jty D
RA
QtWr$x'QtW55AhAq1T7{Q777AdG1T7{Jt
QAAjMa4Kr   c            
      T    t          d                    dddddd                     d S )Nz${:^15}{:^15}{:^15}{:^15}{:^15}{:^15}	Iterationz
Total nfevCostCost reduction	Step norm
OptimalityprintformatrW   r   r   print_header_nonlinearr   !  s>    	
06+|V5E|- -. . . . .r   c           	      h    |d}n|d}|d}n|d}t          | d|d|d| | |d           d S Nz               z^15.2ez^15z^15.4er   )	iterationnfevcostcost_reductionrZ   
optimalitys         r   print_iteration_nonlinearr   '  sq    !*33		 ))		Y
a
aD
a
ad
a
a>
a9
aj
a
a
abbbbbr   c            	      R    t          d                    ddddd                     d S )Nz{:^15}{:^15}{:^15}{:^15}{:^15}r   r   r   r   r   r   rW   r   r   print_header_linearr   6  s<    	
*6+v'7   ! ! ! ! !r   c                 b    |d}n|d}|d}n|d}t          | d|d| | |d           d S r   r   )r   r   r   rZ   r   s        r   print_iteration_linearr   <  si    !*33		 ))		Y
W
WD
W
W
W
WJ
W
W
WXXXXXr   c                     t          | t                    r|                     |          S | j                            |          S )z4Compute gradient of the least-squares cost function.)
isinstancer	   rmatvecro   r   )r^   rO   s     r   compute_gradr   N  s6    !^$$ yy||swwqzzr   c                 J   t          |           rQt          j        |                     d                              d                                                    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   rC   r,   Nr-   )r   r   rf   powerr#   ravelr~   )r^   scale_inv_old	scale_invs      r   compute_jac_scaler   V  s    {{ .Jqwwqzz~~1~5566<<>>C		F1a4a(((#-	$%	)q.!!Jy-88	y=)##r   c                 x     t                       fd} fd} fd}t           j        |||          S )z#Return diag(d) J as LinearOperator.c                 4                         |           z  S N)matvecr   r^   r   s    r   r   z(left_multiplied_operator.<locals>.matveci  s    188A;;r   c                 \    d d t           j        f                             |           z  S r   )r   newaxismatmatXr^   r   s    r   r   z(left_multiplied_operator.<locals>.matmatl  s'    BJ!((1++--r   c                 X                         |                                 z            S r   )r   r   r   s    r   r   z)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  s    A     . . . . . .( ( ( ( ( ( !'&")+ + + +r   c                 x     t                       fd} fd} fd}t           j        |||          S )z#Return J diag(d) as LinearOperator.c                 X                         t          j        |           z            S r   )r   r   r   r   s    r   r   z)right_multiplied_operator.<locals>.matvecz  s!    xxa(((r   c                 \                         | d d t          j        f         z            S r   )r   r   r   r   s    r   r   z)right_multiplied_operator.<locals>.matmat}  s)    xxAaaam,,---r   c                 4                         |           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   v  s    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                 \    t          j                            |           | z  f          S r   )r   hstackr   )r   r^   r_   s    r   r   z(regularized_lsq_operator.<locals>.matvec  s&    y!((1++tax0111r   c                 b    | d          }| d          }                     |          |z  z   S r   r   )r   x1x2r^   r_   r3   s      r   r   z)regularized_lsq_operator.<locals>.rmatvec  s6    rrUqrrUyy}}tby((r   )r   r   )r
   r   r	   )r^   r_   r2   r   r   r3   s   ``   @r   regularized_lsq_operatorr     s     	A7DAq2 2 2 2 2 2) ) ) ) ) ) )
 1q5!*VWEEEEr   Tc                 &   |r)t          | t                    s|                                 } t          |           r+| xj        |                    | j        d          z  c_        n+t          | t                    rt          | |          } n| |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     s    
  Jq.11 FFHH{{ 	!&&&000	A~	&	& %a++	QHr   c                 n   |r)t          | t                    s|                                 } t          |           r;| xj        t          j        |t          j        | j                            z  c_        n?t          | t                    rt          | |          } n| |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1 FFHH{{ 	")Arwqx00111	A~	&	& $Q**	Qqqq"*}Hr   c                 X    | ||z  k     o|dk    }||||z   z  k     }|r|rdS |rdS |rdS dS )z8Check termination condition for nonlinear least squares.rV      r   r"   NrW   )	dFFdx_normx_normr?   ftolxtolftol_satisfiedxtol_satisfieds	            r   check_terminationr    s^    $(]3ut|Nttf}55N . q	 q	 qtr   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^   rO   rhoJ_scales       r   scale_for_robust_loss_functionr    sg    
 !fq3q6zAqD((G GGcMOGQ'	AG%000!33r   )Nr   r   )NN)r   r   )r   )T).__doc__mathr   numpyr   numpy.linalgr   scipy.linalgr   r   r   scipy.sparser   scipy.sparse.linalgr	   r
   finfofloatepsr.   r   r@   rT   r\   rc   rl   rr   ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  rW   r   r   <module>r     sv   1 1                 ; ; ; ; ; ; ; ; ; ; ! ! ! ! ! ! @ @ @ @ @ @ @ @ bhuoo$ $ $N AE/1o o o od0 0 0f  :0 0 0 0f& & & &.$ $ $ $T) ) )
H H H:$ $ $ $N   6) ) )X  D. . .c c c! ! !Y Y Y$  $ $ $ $+ + +"+ + +"F F F,   $   $  4 4 4 4 4r   