
    ^MhL                         d Z ddlZddlmZ ddlmZmZ ddlm	Z	 ddl
mZ ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z  d	 Z!d
 Z"d Z#d Z$dS )a>  Trust Region Reflective algorithm for least-squares optimization.

The algorithm is based on ideas from paper [STIR]_. The main idea is to
account for the presence of the bounds by appropriate scaling of the variables (or,
equivalently, changing a trust-region shape). Let's introduce a vector v:

           | 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

where g is the gradient of a cost function and lb, ub are the bounds. Its
components are distances to the bounds at which the anti-gradient points (if
this distance is finite). Define a scaling matrix D = diag(v**0.5).
First-order optimality conditions can be stated as

    D^2 g(x) = 0.

Meaning that components of the gradient should be zero for strictly interior
variables, and components must point inside the feasible region for variables
on the bound.

Now consider this system of equations as a new optimization problem. If the
point x is strictly interior (not on the bound), then the left-hand side is
differentiable and the Newton step for it satisfies

    (D^2 H + diag(g) Jv) p = -D^2 g

where H is the Hessian matrix (or its J^T J approximation in least squares),
Jv is the Jacobian matrix of v with components -1, 1 or 0, such that all
elements of matrix C = diag(g) Jv are non-negative. Introduce the change
of the variables x = D x_h (_h would be "hat" in LaTeX). In the new variables,
we have a Newton step satisfying

    B_h p_h = -g_h,

where B_h = D H D + C, g_h = D g. In least squares B_h = J_h^T J_h, where
J_h = J D. Note that J_h and g_h are proper Jacobian and gradient with respect
to "hat" variables. To guarantee global convergence we formulate a
trust-region problem based on the Newton step in the new variables:

    0.5 * p_h^T B_h p + g_h^T p_h -> min, ||p_h|| <= Delta

In the original space B = H + D^{-1} C D^{-1}, and the equivalent trust-region
problem is

    0.5 * p^T B p + g^T p -> min, ||D^{-1} p|| <= Delta

Here, the meaning of the matrix D becomes more clear: it alters the shape
of a trust-region, such that large steps towards the bounds are not allowed.
In the implementation, the trust-region problem is solved in "hat" space,
but handling of the bounds is done in the original space (see below and read
the code).

The introduction of the matrix D doesn't allow to ignore bounds, the algorithm
must keep iterates strictly feasible (to satisfy aforementioned
differentiability), the parameter theta controls step back from the boundary
(see the code for details).

The algorithm does another important trick. If the trust-region solution
doesn't fit into the bounds, then a reflected (from a firstly encountered
bound) search direction is considered. For motivation and analysis refer to
[STIR]_ paper (and other papers of the authors). In practice, it doesn't need
a lot of justifications, the algorithm simply chooses the best step among
three: a constrained trust-region step, a reflected step and a constrained
Cauchy step (a minimizer along -g_h in "hat" space, or -D^2 g in the original
space).

Another feature is that a trust-region radius control strategy is modified to
account for appearance of the diagonal C matrix (called diag_h in the code).

Note that all described peculiarities are completely gone as we consider
problems without bounds (the algorithm becomes a standard trust-region type
algorithm very similar to ones implemented in MINPACK).

The implementation supports two methods of solving the trust-region problem.
The first, called 'exact', applies SVD on Jacobian and then solves the problem
very accurately using the algorithm described in [JJMore]_. It is not
applicable to large problem. The second, called 'lsmr', uses the 2-D subspace
approach (sometimes called "indefinite dogleg"), where the problem is solved
in a subspace spanned by the gradient and the approximate Gauss-Newton step
found by ``scipy.sparse.linalg.lsmr``. A 2-D trust-region problem is
reformulated as a 4th order algebraic equation and solved very accurately by
``numpy.roots``. The subspace approach allows to solve very large problems
(up to couple of millions of residuals on a regular PC), provided the Jacobian
matrix is sufficiently sparse.

References
----------
.. [STIR] Branch, M.A., 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.
.. [JJMore] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation
    and Theory," Numerical Analysis, ed. G. A. Watson, Lecture
    N)norm)svdqr)lsmr)OptimizeResult   )step_size_to_boundfind_active_constraints	in_boundsmake_strictly_feasibleintersect_trust_regionsolve_lsq_trust_regionsolve_trust_region_2dminimize_quadratic_1dbuild_quadratic_1devaluate_quadraticright_multiplied_operatorregularized_lsq_operatorCL_scaling_vectorcompute_gradcompute_jac_scalecheck_terminationupdate_tr_radiusscale_for_robust_loss_functionprint_header_nonlinearprint_iteration_nonlinearc                     t          j        |t           j         k              r>t          j        |t           j        k              rt          | |||||||	|
|||||          S t	          | |||||||||	|
|||||          S )N)npallinftrf_no_bounds
trf_bounds)funjacx0f0J0lbubftolxtolgtolmax_nfevx_scaleloss_function	tr_solver
tr_optionsverboses                   W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_lsq/trf.pytrfr4   p   s     
vbRVGm ;bf!5!5 ;b"b$dHg9j'; ; 	; b"b"b$dHg9j'; ; 	;    c                    t          | |z   ||	          rt          ||||          }||| fS t          | |||	          \  }}t          j        |          }||                    t                    xx         dz  cc<   ||z  }||z  }||z  }| |z   }t          |||          \  }}t          ||||	          \  }}t          ||          }|dk    rd|
z
  |z  |z  }||k    r|
|z  }n|}nd}d}||k    r?t          |||||          \  }}}t          |||||          \  }}||z  }||z  }||z  }nt          j        }||
z  }||
z  }t          ||||          }| }||z  }|t          |          z  }t          | |||	          \  }}||k     r|
|z  }n|}t          ||||          \  }}t          ||d|          \  }}||z  }||z  }||k     r||k     r||| fS ||k     r||k     r||| fS ||| fS )zDSelect the best step according to Trust Region Reflective algorithm.diagr   r   )s0r8   )c)r   r   r	   r   copyastypeboolr   minr   r   r    r   )xJ_hdiag_hg_hpp_hdDeltar(   r)   thetap_valuep_stridehitsr_hr
x_on_bound_to_trto_boundr_stride
r_stride_l
r_stride_uabr;   r_valueag_hag	ag_strideag_values                                  r3   select_stepr\      s   QB  $S#s@@@#x'1b"55NHd '#,,CDb 	CA MA8OCQJ &c366HAu$ZB;;KHa 8U##H!||%i8+h6
x)JJJJ

 Z$S#ssHHH1a1q*jA/ / /'xs
!G& JA5LC c3V<<<G4D	
TBDJJE$QB33KHa%H$			c36:::DAq/1aCCIxID)OBWx//#x	7		w11#x4(""r5   c                 d   |                                 }|}|                                 }d}|}d}|j        \  }}|= ||          }dt          j        |d                   z  }t	          |||          \  }}ndt          j        ||          z  }t          ||          }t          |t                    o|dk    }|rt          |          \  }}n|d|z  }}t          ||||          \  }}||dk    xx         ||dk             z  cc<   t          ||z  |dz  z            } | dk    rd} t          ||z  t          j                  }!t          j        ||z             }"|dk    rt          j        ||z   |f          }#n|dk    rd	}$|                    d
d          }%|

|j        dz  }
d	}&d }'d}(d })d }*|dk    rt#                       	 t          ||||          \  }}t          ||z  t          j                  }!|!|	k     rd}'|dk    rt%          |(|||*|)|!           |'||
k    rn||dk    xx         ||dk             z  cc<   |dz  |z  }+||z  |z  },|+|z  }-||"d |<   |dk    rh||+z  |#d |<   |#d |         }.t          j        |,dz            |#|d <   t)          |#d          \  }/}0}1|1j        }1|/j                            |"          }2n#|dk    rt-          ||+          }.|%rJt/          |.|-|- |,          \  }3}4| t          |-          z  }5t1          |3|4d|5          d         }6|6 | dz  z  }$t3          |.|,|$z   dz            }7t5          |7|"fi |d         }8t          j        |-|8f          j        }9t9          |9d          \  }9}:|.                    |9          };t          j        |;j        |;          t          j        |9j        |,z  |9          z   }<|9j                            |-          }=t;          dd|!z
            }>d}*|*dk    ro||
k     rh|dk    rt=          |||2|0|1| |&          \  }?}&}@n/|dk    r)t?          |<|=|           \  }A}:|9                    |A          }?|+|?z  }BtA          ||.|,|-|B|?|+| |||>          \  }C}D}EtC          ||Cz   ||d          }F | |F          }G|dz  }t          |D          }Ht          j"        t          j#        |G                    sd|Hz  } | ||Gd          }Indt          j        |G|G          z  }I||Iz
  }*tI          | |*|E|H|Hd| z  k              \  }J}Kt          |C          })tK          |*||)t          |          |K||          }'|'n|&| |Jz  z  }&|J} |*dk    r||
k     h|*dk    rr|F}|G}|                                 }|I} |||          }|dz  }| ||          }t	          |||          \  }}t          ||          }|rt          ||          \  }}nd})d}*|(dz  }(8|'d}'tM          ||||          }LtO          ||||||!|L|||'
  
        S )Nr         ?r   r$         ?ordexactr           
regularizeTd      Ffull_matricesr7   economicmodegףp=
?r9   initial_alpha)rstep      ?	cost_onlyffffff?)rtol
r@   costr#   r$   grad
optimalityactive_masknfevnjevstatus)(r<   shaper   sumr   dotr   
isinstancestrr   r   r   r    zerosemptypopsizer   r   r8   r   Tr   r   r   r   r   vstackr   maxr   r   r\   r   r   isfiniter   r   r
   r   )Mr#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r@   ff_truery   Jrz   mnrhoru   g	jac_scalescale	scale_invvdvrG   g_normf_augmentedJ_augmentedreg_termrd   alphatermination_status	iteration	step_normactual_reductionrF   rB   rC   rA   UsVufrU   rV   rP   r[   lsmr_opgn_hSrO   JSB_Sg_SrH   rE   n_iterp_SrD   stepstep_hpredicted_reductionx_newf_newstep_h_normcost_new	Delta_newratiorx   sM                                                                                r3   r"   r"      sx   
		A
AVVXXFD
AD7DAq mARVCF^^#-aC8811RVAq\\!QA7C((=W-=I 0,Q//yy"AKyaB++EArbAgJJJ)B!G$$JJJi!S&())Ezz!a%RV$$$F(1q5//KGhAqz**	f		^^L$77
7S=EII!||   A!!QB//2a!e(((D==!"a<<%it=M&/9 9 9 )TX-=-= 	
"'


ia((


 sFUN R%
 !eBQB!eKObqb/C gfck22KO+U;;;GAq!A%%BB&  +Aq11C 0)#sSDvFFF1S		)0Aq%@@C$9uax/.sVh5F4LMMG;;
;;A>D	3+&&(Aaj)))DAqB&r""RVAC&L!%<%<<C#''#,,C E1v:&&!##xG##%;q"aE&@ &@ &@"UFFf$$.sC??QeeCjjCA0;3QQr2u1F 1F-D&- +1t8R1EEEECJJEAIDv,,K6"+e,,-- {* ((=$???u!5!55#h/')<[4%<7 9  9Iu T

I!2 $	477E4"O "O!-UY&&EEO !##xR aAAVVXXFDAq		AAID(#mA&&5aC@@1Q""A C#4Q	#B#B yI Q	CAF !)!R$???K
$Ffd!# # # #r5   c                 	   |                                 }|}|                                 }d}|}d}|j        \  }}|
= |
|          }dt          j        |d                   z  }t	          |||          \  }}ndt          j        ||          z  }t          ||          }t          |	t                    o|	dk    }|rt          |          \  }}n|	d|	z  }}t          ||z            }|dk    rd}|dk    r.d}|                    dd          }|                    d	d
          }|
|j        dz  }d} d }!d}"d }#d }$|dk    rt                       	 t          |t          j                  }%|%|k     rd}!|dk    rt          |"|||$|#|%           |!||k    rn!|}&|&|z  }'|dk    r<||&z  }(t!          |(d          \  })}*}+|+j        }+|)j                            |          },n|dk    rt%          ||&          }(|rHt'          |(|'|'           \  }-}.|t          |'          z  }/t)          |-|.d|/          d         }0|0 |dz  z  }|dz  |z   dz  }1t+          |(|fd|1i|d         }2t          j        |'|2f          j        }3t/          |3d          \  }3}4|(                    |3          }5t          j        |5j        |5          }6|3j                            |'          }7d}$|$dk    rS||k     rL|dk    rt1          |||,|*|+||           \  }8} }9n/|dk    r)t3          |6|7|          \  }:}4|3                    |:          }8t5          |(|'|8           };|&|8z  }<||<z   }= | |=          }>|dz  }t          |8          }?t          j        t          j        |>                    sd|?z  }|
 |
|>d
          }@ndt          j        |>|>          z  }@||@z
  }$t;          ||$|;|?|?d|z  k              \  }A}Bt          |<          }#t=          |$||#t          |          |B||          }!|!n| ||Az  z  } |A}|$dk    r||k     L|$dk    rr|=}|>}|                                 }|@} |||          }|dz  }|
 |
|          }t	          |||          \  }}t          ||          }|rt          ||          \  }}nd}#d}$|"dz  }"h|!d}!t          j        |          }CtA          ||||||%|C|||!
  
        S )Nr   r^   r   r$   r_   r   damprc   rd   Tre   rf   r`   rb   Frg   ri   rj   r9   rl   ro   rp   rr   rt   )!r<   r|   r   r}   r   r~   r   r   r   r   r   r   r   r   r    r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   
zeros_liker   )Dr#   r$   r%   r&   r'   r*   r+   r,   r-   r.   r/   r0   r1   r2   r@   r   r   ry   r   rz   r   r   r   ru   r   r   r   r   rG   r   r   rd   r   r   r   r   r   r   rF   rC   rA   r   r   r   r   rU   rV   rP   r[   	damp_fullr   r   rO   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rx   sD                                                                       r3   r!   r!     s   
		A
AVVXXFD
AD7DAq mARVCF^^#-aC8811RVAq\\!QA7C((=W-=I 0,Q//yy"AKyi  EzzF~~fc**^^L$77
7S=EII!||   eaRV$$$D==!"a<<%it=M&/9 9 9 )TX-=-=!ea%C#U333GAq!ABB&  +Aq11C 0)#sSD991S		)0Aq%@@C$9uax/q8+c1IQ==Y=*==a@D	3+&&(Aaj)))DAqB&r""C#''#,,C!##xG##(>q"aE)@ )@ )@%vvf$$.sC??Qs#5c3#G#G"Gv:DHECJJEAIDv,,K6"+e,,-- {* ((=$???u!5!55#h/')<[4%<7 9  9Iu T

I!2 $	477E4"O "O!-UY&&EEM !##xP aAAVVXXFDAq		AAID(#mA&&5aC@@1Q""A C#4Q	#B#B yI Q	KeN !-""K
$Ffd!# # # #r5   )%__doc__numpyr   numpy.linalgr   scipy.linalgr   r   scipy.sparse.linalgr   scipy.optimizer   commonr	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r4   r\   r"   r!    r5   r3   <module>r      s  ^ ^~                           $ $ $ $ $ $ ) ) ) ) ) )                                           ; ; ; J# J# J#ZA# A# A#H_# _# _# _# _#r5   