
    9i/                         S r SSKrSSKJrJr  SSKJrJrJ	r	  SSK
Jr  SSKJr  SSKJrJrJrJrJrJrJrJrJrJrJrJr  S	 rS
 rS r SS jrg)a	  
Dogleg algorithm with rectangular trust regions for least-squares minimization.

The description of the algorithm can be found in [Voglis]_. The algorithm does
trust-region iterations, but the shape of trust regions is rectangular as
opposed to conventional elliptical. The intersection of a trust region and
an initial feasible region is again some rectangle. Thus, on each iteration a
bound-constrained quadratic optimization problem is solved.

A quadratic problem is solved by well-known dogleg approach, where the
function is minimized along piecewise-linear "dogleg" path [NumOpt]_,
Chapter 4. If Jacobian is not rank-deficient then the function is decreasing
along this path, and optimization amounts to simply following along this
path as long as a point stays within the bounds. A constrained Cauchy step
(along the anti-gradient) is considered for safety in rank deficient cases,
in this situations the convergence might be slow.

If during iterations some variable hit the initial bound and the component
of anti-gradient points outside the feasible region, then a next dogleg step
won't make any progress. At this state such variables satisfy first-order
optimality conditions and they are excluded before computing a next dogleg
step.

Gauss-Newton step can be computed exactly by `numpy.linalg.lstsq` (for dense
Jacobian matrices) or by iterative procedure `scipy.sparse.linalg.lsmr` (for
dense and sparse matrices, or Jacobian being LinearOperator). The second
option allows to solve very large problems (up to couple of millions of
residuals on a regular PC), provided the Jacobian matrix is sufficiently
sparse. But note that dogbox is not very good for solving problems with
large number of constraints, because of variables exclusion-inclusion on each
iteration (a required number of function evaluations might be high or accuracy
of a solution will be poor), thus its large-scale usage is probably limited
to unconstrained problems.

References
----------
.. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region Dogleg
            Approach for Unconstrained and Bound Constrained Nonlinear
            Optimization", WSEAS International Conference on Applied
            Mathematics, Corfu, Greece, 2004.
.. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization, 2nd edition".
    N)lstsqnorm)LinearOperatoraslinearoperatorlsmr)OptimizeResult)_call_callback_maybe_halt   )step_size_to_bound	in_boundsupdate_tr_radiusevaluate_quadraticbuild_quadratic_1dminimize_quadratic_1dcompute_gradcompute_jac_scalecheck_terminationscale_for_robust_loss_functionprint_header_nonlinearprint_iteration_nonlinearc                 d   ^ ^^ T R                   u  p4U UU4S jnU UU4S jn[        X44XV[        S9$ )zCompute LinearOperator to use in LSMR by dogbox algorithm.

`active_set` mask is used to excluded active variables from computations
of matrix-vector products.
c                 r   > U R                  5       R                  5       nSUT'   TR                  U T-  5      $ Nr   )ravelcopymatvec)xx_freeJop
active_setds     Z/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/scipy/optimize/_lsq/dogbox.pyr   lsmr_operator.<locals>.matvecB   s2    !zzz!a%      c                 :   > TTR                  U 5      -  nSUT'   U$ r   )rmatvec)r   rr   r    r!   s     r"   r&   lsmr_operator.<locals>.rmatvecG   s#    A*r$   )r   r&   dtype)shaper   float)r   r!   r    mnr   r&   s   ```    r"   lsmr_operatorr.   :   s-     99DA!

 1&NNr$   c                 (   X -
  nX0-
  n[         R                  " XA* 5      n[         R                  " XQ5      n[         R                  " Xd5      n[         R                  " Xu5      n	[         R                  " Xa* 5      n
[         R                  " Xq5      nXgXX4$ )a  Find intersection of trust-region bounds and initial bounds.

Returns
-------
lb_total, ub_total : ndarray with shape of x
    Lower and upper bounds of the intersection region.
orig_l, orig_u : ndarray of bool with shape of x
    True means that an original bound is taken as a corresponding bound
    in the intersection region.
tr_l, tr_u : ndarray of bool with shape of x
    True means that a trust-region bound is taken as a corresponding bound
    in the intersection region.
)npmaximumminimumequal)r   	tr_boundslbublb_centeredub_centeredlb_totalub_totalorig_lorig_utr_ltr_us               r"   find_intersectionr?   O   sw     &K&Kzz+z2Hzz+1HXXh,FXXh,F88Hj)D88H(Dvt99r$   c                    [        XXg5      u  ppp[        R                  " U [        S9n[	        XU	5      (       a  XS4$ [        [        R                  " U 5      U* X5      u  nn[        X4SU5      S   * U-  nUU-
  n[        UUX5      u  nnSUUS:  U
-  '   SUUS:  U-  '   [        R                  " US:  U-  US:  U-  -  5      nUUU-  -   UU4$ )a  Find dogleg step in a rectangular region.

Returns
-------
step : ndarray, shape (n,)
    Computed dogleg step.
bound_hits : ndarray of int, shape (n,)
    Each component shows whether a corresponding variable hits the
    initial bound after the step is taken:
        *  0 - a variable doesn't hit the bound.
        * -1 - lower bound is hit.
        *  1 - upper bound is hit.
tr_hit : bool
    Whether the step hit the boundary of the trust-region.
r)   Fr   r
   )r?   r0   
zeros_likeintr   r   r   any)r   newton_stepgabr4   r5   r6   r9   r:   r;   r<   r=   r>   
bound_hits	to_bounds_cauchy_step	step_diff	step_sizehitstr_hits                         r"   dogleg_steprR   l   s      6G	b62H q,J11--%bmmA&6HOLIq )q)<Q??!CKk)I(i)1=OIt&(JqF"#&'JqF"#VVTAX%T(99:FY..
FBBr$   c                    UnUR                  5       nSnUnSnUb5  U" U5      nS[        R                  " US   5      -  n[        UUU5      u  nnOS[        R                  " UU5      -  n[        UU5      n[        U[        5      =(       a    US:H  nU(       a  [        U5      u  nnOUSU-  nn[        UU-  [        R                  S9nUS:X  a  Sn[        R                  " U[        S9nSU[        R                  " X%5      '   SU[        R                  " X&5      '   Un[        R                  " U5      nU
c  UR                  S	-  n
S n Sn!S n"S n#US
:X  a
  [!        5          UU-  S:  n$U$) n%UU%   n&UR                  5       n'SUU$'   [        U[        R                  S9n(U(U	:  a  Sn US
:X  a  [#        U!UUU#U"U(5        U c  UU
:X  a  GOUU%   n)UU%   n*UU%   n+UU%   n,US:X  a*  US S 2U%4   n-[%        U-U* SS9S   n.['        U-U&U&* 5      u  n/n0OHUS:X  aB  [)        U5      n1[+        U1UU$5      n2[-        U2U40 UD6S   U%   * n.U.U,-  n.['        U1UU* 5      u  n/n0Sn#U#S::  GaL  UU
:  GaE  UU,-  n3[/        U)W.U&W/W0U3U*U+5      u  n4n5n6UR1                  S5        U4UU%'   US:X  a  [3        W-U&U45      * n7OUS:X  a  [3        W1UU5      * n7[        R4                  " UU-   XV5      n8U " U85      n9US-  n[        UU-  [        R                  S9n:[        R6                  " [        R8                  " U95      5      (       d  SU:-  nM  Ub  U" U9SS9n;OS[        R                  " U9U95      -  n;UU;-
  n#[;        UU#W7U:U65      u  nn<[        U5      n"[=        U#UU"[        U5      U<Xx5      n U b  OU#S::  a	  UU
:  a  GME  U#S:  a  W5UU%'   W8nUS:H  n=UU=   UU='   US:H  n=UU=   UU='   W9nUR                  5       nW;nU" U5      nUS-  nUb  U" U5      n[        UUU5      u  nn[        UU5      nU(       a  [        UU5      u  nnOSn"Sn#U!S-  n!Ub%  [?        UUU!US9n>W;U>S'   [A        UU>5      (       a  Sn OGM  U c  Sn [?        UUUUU'U(UUUU S9
$ )Nr
   g      ?r   jac)ordg      ?rA   rB   d      Texact)rcondr   g      g        g      ?)	cost_only)r   funnitnfevcost)
r   r^   r[   rT   grad
optimalityactive_maskr]   njevstatus)!r   r0   sumr   dotr   
isinstancestrr   r   infrC   rD   r3   
empty_likesizer   r   r   r   r   r.   r   rR   fillr   clipallisfiniter   r   r   r	   )?r[   rT   x0f0J0r5   r6   ftolxtolgtolmax_nfevx_scaleloss_function	tr_solver
tr_optionsverbosecallbackff_truer]   Jrc   rhor^   rG   	jac_scalescale	scale_invDeltaon_boundr   steptermination_status	iteration	step_normactual_reductionr    free_setg_freeg_fullg_normr   lb_freeub_free
scale_freeJ_freerF   rH   rI   r   lsmr_opr4   	step_freeon_bound_freerQ   predicted_reductionx_newf_newstep_h_normcost_newratiomaskintermediate_results?                                                                  r"   dogboxr      s_   
AVVXFD
AD ARVVCF^#-aC81RVVAq\!QA7C(=W-=I,Q/y"AKyiRVV,Ez}}Rs+H!#HRXXb!"HRXXb
A==D77S=II!| 
\A%
;8*aRVV$D=!"a<%it=M&/9 )TX-=8X,X,8_
 q({^F"5a8K &ffvg>DAq& "1%C $C
;G9j9!<XFFK:%K &c1qb1DAq!#x
*I/:VQ9gw0P,I}f IIcN&DNG#'9&&:C(E 'E#f$'9#q$'G&G# GGAHb-EJEAIDti/RVV<K66"++e,--{* (($?u!55#h+')<VLE5
 T
I!2 $	47E4"O "-Y !#x\ a!.HXAr>DhAdGq=DhAdGAVVXFDAAAID(#A&5aC@1Q"A#4Q	#B yI Q	 "0	#6*2'(-  &("[ ^ !
$F64d;MO Or$   )N)__doc__numpyr0   numpy.linalgr   r   scipy.sparse.linalgr   r   r   scipy.optimizer   scipy._lib._utilr	   commonr   r   r   r   r   r   r   r   r   r   r   r   r.   r?   rR   r    r$   r"   <module>r      sS   )T  $ F F ) 67 7 7 7O*::(CX DHBOr$   