Ë
    âQ(h¢-  ã                   ó�   — d Z ddlZddlmZmZ ddlmZmZ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 d„ Zd	„ Zd
„ Zd„ Zy)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é   )Ú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                 ól   ‡ ‡‡— ‰ j                   \  }}ˆ ˆˆfd„}ˆ ˆˆfd„}t        ||f||t        ¬«      S )z¬Compute 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   •— | j                  «       j                  «       }d|‰<   ‰j                  | ‰z  «      S ©Nr   )ÚravelÚcopyÚmatvec)ÚxÚx_freeÚJopÚ
active_setÚds     €€€úX/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/scipy/optimize/_lsq/dogbox.pyr   zlsmr_operator.<locals>.matvec@   s2   ø€ Ø—‘“—‘Ó!ˆØˆˆzÑØ�z‰z˜!˜a™%Ó Ð ó    c                 ó:   •— ‰‰j                  | «      z  }d|‰<   |S r   )Úrmatvec)r   Úrr   r   r    s     €€€r!   r$   zlsmr_operator.<locals>.rmatvecE   s#   ø€ Ø�—‘˜A“ÑˆØˆˆ*‰Øˆr"   )r   r$   Údtype)Úshaper   Úfloat)r   r    r   ÚmÚnr   r$   s   ```    r!   Úlsmr_operatorr+   8   s3   ú€ ð �9‰9�D€A€qö!ö
ô
 ˜1˜a˜&¨¸ÌÔNÐNr"   c                 ó2  — || z
  }|| z
  }t        j                  || «      }t        j                  ||«      }t        j                  ||«      }t        j                  ||«      }	t        j                  || «      }
t        j                  ||«      }||||	|
|fS )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<   M   s�   € ð �q‘&€KØ�q‘&€Kä�z‰z˜+¨	 zÓ2€HÜ�z‰z˜+ yÓ1€Hä�X‰X�h Ó,€FÜ�X‰X�h Ó,€Fä�8‰8�H˜y˜jÓ)€DÜ�8‰8�H˜iÓ(€Dà�X˜v v¨t°TÐ9Ð9r"   c                 ó°  — t        | |||«      \  }}	}
}}}t        j                  | t        ¬«      }t	        |||	«      r||dfS t        t        j                  | «      | ||	«      \  }}t        ||d|«      d    |z  }||z
  }t        ||||	«      \  }}d||dk  |
z  <   d||dkD  |z  <   t        j                  |dk  |z  |dkD  |z  z  «      }|||z  z   ||fS )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<   r-   Ú
zeros_likeÚintr   r
   r   Úany)r   Únewton_stepÚgÚaÚbr1   r2   r3   r6   r7   r8   r9   r:   r;   Ú
bound_hitsÚ	to_boundsÚ_Úcauchy_stepÚ	step_diffÚ	step_sizeÚhitsÚtr_hits                         r!   Údogleg_steprO   j   s  € ô  6GØ	ˆ9�b˜"ó6Ñ2€Hˆh˜ ¨¨dô —‘˜q¬Ô,€Jä�˜h¨Ô1Ø˜J¨Ð-Ð-ä%¤b§m¡m°AÓ&6¸¸¸HÀhÓO�L€Iˆqô )¨¨A¨q°)Ó<¸QÑ?Ð?À!ÑC€Kà˜kÑ)€IÜ(¨°iØ)1°8ó=�O€Iˆtà&(€J��q‘˜FÑ"Ñ#Ø&'€J��q‘˜FÑ"Ñ#Ü�V‰V�T˜A‘X Ñ%¨°©°TÑ(9Ñ9Ó:€Fà˜ YÑ.Ñ.°
¸FÐBÐBr"   c                 ój  — |}|j                  «       }d}|}d}|�4 ||«      }dt        j                  |d   «      z  }t        |||«      \  }}ndt        j                  ||«      z  }t        ||«      }t        |t        «      xr |dk(  }|rt        |«      \  }}n|d|z  }}t        ||z  t        j                  ¬«      }|dk(  rd}t        j                  |t        ¬«      }d|t        j                  ||«      <   d|t        j                  ||«      <   |}t        j                  |«      }|
€|j                  d	z  }
d }d} d }!d }"|d
k(  r
t!        «        	 ||z  dk  }#|# }$||$   }%|j                  «       }&d||#<   t        |t        j                  ¬«      }'|'|	k  rd}|d
k(  rt#        | |||"|!|'«       |€||
k(  r�nb||$   }(||$   })||$   }*||$   }+|dk(  r-|d d …|$f   },t%        |,| d¬«      d   }-t'        |,|%|% «      \  }.}/nG|dk(  rBt)        |«      }0t+        |0||#«      }1t-        |1|fi |¤Žd   |$    }-|-|+z  }-t'        |0|| «      \  }.}/d}"|"dk  �rB||
k  �r<||+z  }2t/        |(-|%./|2|)|*«      \  }3}4}5|j1                  d«       |3||$<   |dk(  rt3        ,|%|3«       }6n|dk(  rt3        0||«       }6t        j4                  ||z   ||«      }7 | |7«      }8|dz  }t        ||z  t        j                  ¬«      }9t        j6                  t        j8                  |8«      «      sd|9z  }Œ×|� ||8d¬«      }:ndt        j                  |8|8«      z  }:||:z
  }"t;        ||"6|9|5«      \  }};t        |«      }!t=        |"||!t        |«      |;||«      }|�n|"dk  r||
k  r�Œ<|"dkD  r{4||$<   7}|dk(  }<||<   ||<<   |dk(  }<||<   ||<<   8}|j                  «       }:} |||«      }|dz  }|� ||«      }t        |||«      \  }}t        ||«      }|rt        ||«      \  }}nd}!d}"| dz  } �ŒÇ|€d}t?        |||||&|'||||¬«
      S )Nr	   g      à?r   Újac)Úordg      ð?r>   r?   éd   é   TÚexact)Úrcondr   g      ð¿g        g      Ð?)Ú	cost_only)
r   ÚcostÚfunrQ   ÚgradÚ
optimalityÚactive_maskÚnfevÚnjevÚstatus) r   r-   Úsumr   Údotr   Ú
isinstanceÚstrr   r   Úinfr@   rA   r0   Ú
empty_likeÚsizer   r   r   r   r   r+   r   rO   Úfillr   ÚclipÚallÚisfiniter   r   r   )=rY   rQ   Úx0Úf0ÚJ0r2   r3   ÚftolÚxtolÚgtolÚmax_nfevÚx_scaleÚloss_functionÚ	tr_solverÚ
tr_optionsÚverboseÚfÚf_truer]   ÚJr^   ÚrhorX   rD   Ú	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_freerC   rE   rF   r   Úlsmr_opr1   Ú	step_freeÚon_bound_freerN   Úpredicted_reductionÚx_newÚf_newÚstep_h_normÚcost_newÚratioÚmasks=                                                                r!   Údogboxr—   •   s   € à
€AØ�V‰V‹X€FØ€Dà
€AØ€DàÐ Ù˜AÓˆØ”R—V‘V˜C ™F“^Ñ#ˆÜ-¨a°°CÓ8‰ˆ‰1à”R—V‘V˜A˜q“\Ñ!ˆä�Q˜Ó€Aä˜7¤CÓ(Ò=¨W¸Ñ-=€IÙÜ,¨QÓ/Ñˆ‰yà" A¨¡Kˆyˆä��i‘¤R§V¡VÔ,€EØ�‚zØˆä�}‰}˜R¤sÔ+€HØ!#€HŒR�X‰X�b˜"ÓÑØ!"€HŒR�X‰X�b˜"ÓÑà
€AÜ�=‰=˜Ó€DàÐØ—7‘7˜S‘=ˆàÐØ€IØ€IØÐà�!‚|ÜÔ à
Ø ‘\ AÑ%ˆ
Ø�;ˆà�8‘ˆØ—‘“ˆØˆˆ*‰ä�aœRŸV™VÔ$ˆØ�DŠ=Ø!"Ðà�aŠ<Ü% i°°tÐ=MØ&/°ô9ð Ð)¨T°XÒ-=Ùà�8‘ˆØ�X‘,ˆØ�X‘,ˆØ˜8‘_ˆ
ð ˜ÒØ’q˜(�{‘^ˆFÜ ¨¨°"Ô5°aÑ8ˆKô & f¨f°v°gÓ>‰DˆA‰qØ˜&Ò Ü" 1Ó%ˆCô $ C¨°
Ó;ˆGÜ ¨Ñ9¨jÑ9¸!Ñ<¸XÑFÐFˆKØ˜:Ñ%ˆKô & c¨1¨q¨bÓ1‰DˆAˆqàÐØ !Ó#¨¨x«Ø 
Ñ*ˆIä/:Ø˜ V¨Q°°9¸gÀwó0PÑ,ˆI�} fð �I‰I�cŒNØ&ˆD�‰Nà˜GÒ#Ü'9¸&À&Ø:Có(Eð 'EÑ#à˜fÒ$Ü'9¸#¸qÀ$Ó'GÐ&GÐ#ô —G‘G˜A ™H b¨"Ó-ˆEá˜“JˆEØ�A‰IˆDä˜t iÑ/´R·V±VÔ<ˆKä—6‘6œ"Ÿ+™+ eÓ,Ô-Ø˜{Ñ*�Øð Ð(Ù(¨¸$Ô?‘à¤§¡¨¨uÓ!5Ñ5�Ø# h™Ðä+ØÐ'Ð)<Ø˜Vó‰LˆE�5ô
 ˜T›
ˆIÜ!2Ø  $¨	´4¸³7¸EÀ4Èó"OÐð "Ð-ØðY  !Ò#¨¨x¬ð\ ˜aÒØ!.ˆH�XÑàˆAà˜r‘>ˆDØ˜‘hˆAˆd‰GØ˜q‘=ˆDØ˜‘hˆAˆd‰GàˆAØ—V‘V“XˆFàˆDá�A�q“	ˆAØ�A‰IˆDàÐ(Ù# AÓ&�Ü5°a¸¸CÓ@‘��1ä˜Q Ó"ˆAáÜ#4°Q¸	Ó#BÑ �‘yàˆIØ Ðà�Q‰ˆ	ñC ðF Ð!ØÐäØ
�$˜F¨°À6Ø 4¨dÐ;MôOð Or"   )Ú__doc__Únumpyr-   Únumpy.linalgr   r   Úscipy.sparse.linalgr   r   r   Úscipy.optimizer   Úcommonr
   r   r   r   r   r   r   r   r   r   r   r   r+   r<   rO   r—   © r"   r!   ú<module>rŸ      sI   ðñ)óT ß $ç FÑ FÝ )÷7÷ 7÷ 7ó 7òOò*:ò:(CóVvOr"   