
    Џkhpb                         d Z ddlZddlmZ ddlmZmZm	Z	m
Z
 ddlmZmZ ddlmZmZmZmZmZ d Zdej*                  d	efd
Zd Zy)a  
This module provides subroutines concerning the trust-region calculations of COBYLA.

Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.

Dedicated to late Professor M. J. D. Powell FRS (1936--2015).

Python translation by Nickolai Belakovski.
    N   )	DEBUGGINGREALMINREALMAXEPS)qradd_Rdiagqrexc_Rdiag)isminormatprodinprodlsqrprimasumc                 $   | j                   d   }| j                   d   }t        rI|dk\  sJ |dk\  sJ t        j                  |      |k(  sJ t        j                  |      |k(  sJ |dkD  sJ t        j                  |dz         }t        j                  |dz   t
              }d}t        j                  |      }	t        j                  ||f      }
t        j                  | |j                  |df      g      }t        j                  |dg      }t        |dz         D ]W  }t        t        |dd|f               x}dkD  s$t        dt        z  d|z        }|dd|fxx   |z  cc<   ||xx   |z  cc<   Y t        |d| |d|ddd|f   |d| ||	|d| |
	      \  |d| }}	|d| }
t        ||d||||	||
	      \  }}}	}}
t        rGt        t        j                  |	            sJ t        j                  j!                  |	      d|z  k  sJ |	S )a  
    This function calculated an n-component vector d by the following two stages. In the first
    stage, d is set to the shortest vector that minimizes the greatest violation of the constraints
        A.T @ D <= B,  K = 1, 2, 3, ..., M,
    subject to the Euclidean length of d being at most delta. If its length is strictly less than
    delta, then the second stage uses the resultant freedom in d to minimize the objective function
        G.T @ D
    subject to no increase in any greatest constraint violation.

    It is possible but rare that a degeneracy may prevent d from attaining the target length delta.

    cviol is the largest constraint violation of the current d: max(max(A.T@D - b), 0)
    icon is the index of a most violated constraint if cviol is positive.

    nact is the number of constraints in the active set and iact[0], ..., iact[nact-1] are their indices,
    while the remainder of the iact contains a permutation of the remaining constraint indicies.
    N.B.: nact <= min(num_constraints, num_vars). Obviously nact <= num_constraints. In addition, the constraints
    in iact[0, ..., nact-1] have linearly independent gradients (see the comments above the instruction
    that delete a constraint from the active set to make room for the new active constraint with index iact[icon]);
    it can also be seen from the update of nact: starting from 0, nact is incremented only if nact < n.

    Further, Z is an orthogonal matrix whose first nact columns can be regarded as the result of
    Gram-Schmidt applied to the active constraint gradients. For j = 0, 1, ..., nact-1, the number
    zdota[j] is the scalar product of the jth column of Z with the gradient of the jth active
    constraint. d is the current vector of variables and here the residuals of the active constraints
    should be zero. Further, the active constraints have nonnegative Lagrange multipliers that are
    held at the beginning of vmultc. The remainder of this vector holds the residuals of the inactive
    constraints at d, the ordering of the components of vmultc being in agreement with the permutation
    of the indices of the constraints that is in iact. All these residuals are nonnegative, which is
    achieved by the shift cviol that makes the least residual zero.

    N.B.:
    0. In Powell's implementation, the constraints are A.T @ D >= B. In other words, the A and B in
    our implementation are the negative of those in Powell's implementation.
    1. The algorithm was NOT documented in the COBYLA paper. A note should be written to introduce it!
    2. As a major part of the algorithm (see trstlp_sub), the code maintains and updates the QR
    factorization of A[iact[:nact]], i.e. the gradients of all the active (linear) constraints. The
    matrix Z is indeed Q, and the vector zdota is the diagonal of R. The factorization is updated by
    Givens rotations when an index is added in or removed from iact.
    3. There are probably better algorithms available for the trust-region linear programming problem.
       r   dtypeNg   mBr   )shaper   npsizezerosinthstackreshaperangemaxabsr   
trstlp_suballisfinitelinalgnorm)Abdeltagnum_constraintsnum_varsvmultciactnactdzA_augb_augimaxvalmodscals                   a/var/www/teggl/fontify/venv/lib/python3.12/site-packages/scipy/_lib/pyprima/cobyla/trustregion.pytrstlpr3      s   X ggajOwwqzH 1}}!###wwqzX%%%wwqz_,,,qyy XXo)*F88Oa's3DD
A
(H%&A IIq!))XqM234EIIq!fE
 ?1$%  E!Q$K())FT1!G)QvX.G!Q$K7"K!HH	  DNdScTcNdfjlmotuv  yI  zI  yI  vI  pJ  LQ  Rb  Sb  Lc  ej  lm  ou  vF  wF  oG  IJ  DK@D	/D!V,<_%=q  *$auaQWYZ[D$61 2;;q>"""yy~~a AI---H    r)   r*   c	                    t        j                  |j                  d         }	t        j                  t        j                  |            }
t        j                  t        j                  |d            }t        j                  |d      }t        j                  |d      }t        rI|dk\  sJ |dk(  s|dk(  sJ |dk\  r|dk(  s|dk\  r|dk(  sJ t        j                  |      |k(  sJ t        j                  |       |k(  sJ t        j                  |      |k(  sJ t        j                  |      |k(  sJ t        j                  |d      |k(  rt        j                  |d      |k(  sJ |dkD  sJ |dk(  rxt        t        j                  |            r%t         j                  j                  |      d|z  k  sJ |dk\  r|t        j                  ||      k  sJ t        |d|       dk\  sJ |dk(  rt        j                  d|dz
  |t              } d}t        j                  |      }t        j                  t        j                  d|             }||z   }t        j                  |      }|dk(  s|dk  r| ||||fS t        t        j                  |            r| ||||fS t        j                   |       }|}t        j                  t#        |            }nxt%        ||      ||z  k\  r| ||||fS |dz
  | |dz
  <   d||dz
  <   |dz
  }|dz
  }t        j                  t        j                  dt'        ||ddd|f         |d| z
              }t)        |      D cg c]  }t%        |dd|f   |dd| |   f         ! c}|d| t*        }|}d}t        j                  ddt        ||      z        }t)        |      D ]/  }t        rt        |dk\        sJ |dk(  r|}nt%        ||dd|dz
  f         }||k  s||kD  r|}d}n|dz  }t        j                  ||      }|dk(  r n||k\  r|d| |	d| |}t-        |dd| |   f   |||      \  }}}||dz   k(  r8||dz   k7  r&||dz
     df|||dz
  g<   | |dz
  |g   | ||dz
  g<   nNd||dz
  <   nDt/        |dd| d| f   |dd| |   f   |ddd|f   |	d|       |
d| t1        t        j2                  |
d| dkD  | d| |k              s nd	|
|| t)        |      D cg c]#  }|
|   dkD  r| |   |k  r||   |
|   z  nt*        % }}t5        |d|       }t        j6                  t        j                  t#        |d|             |d| ||
d| z  z
        |d| t        j                  ||dz
           st9        ||dz
           t:        dz  k  r n7d|f|||dz
  g<   | |dz
  |g   | ||dz
  g<   |dk(  rj| |dz
     |dz
  k7  r\|dk  r nt=        |dd| d| f   ||d| |dz
        \  }|d| | |dz
  |dz
  g   | |dz
  |dz
  g<   ||dz
  |dz
  g   ||dz
  |dz
  g<   t        j                  ||dz
           st9        ||dz
           t:        dz  k  r nq|dk(  r6t%        ||dd| |dz
     f         dz   ||dz
     z  |dd|dz
  f   z  z  }nd	||dz
     z  |dd|dz
  f   z  }nt=        |dd| d| f   ||d| |      \  }|d| g | |dz   | | |   | || g ||dz   | ||   ||| |dz  }|dk(  r|dk  r n|dkD  r9t        j                  ||dz
           st9        ||dz
           t:        dz  k  r n|dk(  r!t%        ||dd|f         |dd|f   z  z  }nd	||dz
     z  |dd|dz
  f   z  }||z  t%        ||      z
  }t%        ||      }t%        ||      }|dk  s$|t:        |z  |z  k  st        j                  |      r nt        t        j>                  ||z  ||z  z         t9        |      t        j>                  ||z              } |dkD  r	|| |z   z  }!n| |z
  |z  }!|!dk  st        j                  |!      s ny|dk(  rtA        ||!      r net5        |!|      }!||!|z  z   }"|dk(  rFt        j                  t        j                  dt'        |"|dd| d| f         || d|    z
              }t/        |dd| d| f   |"|ddd|f   |d|        |
d| |dk(  rt        d|
|dz
           |
|dz
  <   |t'        |"|dd| f         ||    z
  z
  }#t'        t9        |"      t9        |dd| f               t9        ||          z   |z   }$d|#tA        |#|$      <   |#|| |
|| t)        t#        |
            D cg c]!  }|
|   dk  r||   ||   |
|   z
  z  nt*        # }}t        jB                  t        j                  d|            dz
  }t5        t        j                  d|            }|}%d|z
  |z  ||"z  z   }t        j6                  dd|z
  |z  ||
z  z         }t        j                  tE        t9        |                  r't        j                  tE        t9        |                  s|%} nJ|dk(  r6t        j                  t        j                  dt'        ||      |z
              }|dk  s||k\  s0 n t        rt        j                  |       |k(  sJ t        j                  |      |k(  sJ t        |dk\        sJ t        j                  |      |k(  sJ t        t        j                  |            sJ t         j                  j                  |      d|z  k  sJ t        j                  |d      |k(  rt        j                  |d      |k(  sJ |dk\  r|t        j                  ||      k  sJ | ||||fS c c}w c c}w c c}w )
aE  
    This subroutine does the real calculations for trstlp, both stage 1 and stage 2.
    Major differences between stage 1 and stage 2:
    1. Initialization. Stage 2 inherits the values of some variables from stage 1, so they are
    initialized in stage 1 but not in stage 2.
    2. cviol. cviol is updated after at iteration in stage 1, while it remains a constant in stage2.
    3. sdirn. See the definition of sdirn in the code for details.
    4. optnew. The two stages have different objectives, so optnew is updated differently.
    5. step. step <= cviol in stage 1.
    r   r   r   Nr   i'  d      )#r   r   r   r   r   r   r   r    r!   minimumlinspacer   r   appendeyeisnan	nanargmaxlenr   r   r   r   r   r   anylogical_andminmaximumr   r   r	   sqrtr
   argminr   )&r)   r*   stager"   r#   r$   r+   r(   r,   zdasavvmultdzdotamconr'   cvioliconr&   sdirnkoptoldnactoldnfailmaxiteriteroptnewnactsavr/   fracmultfracddsssdsqrtdstepdnewcvshiftcvsabsdolds&                                         r2   r   r   t   s    XXaggaj!FXXbggfo&FHHRWWQ]#E 771a=Dwwq!}H 1}}zUaZ''	eqjdaiEQJGGwwqzT!!!wwt}$$$wwv$&&&wwqzX%%%wwq!}(RWWQ]h-FFFqyyA:r{{1~&299>>!+<E	+III19D()C!CCCvet}%***
 z{{1d1fd#6HHXryyQB'(FF819
q&!++rxx{q&!++<<#DQ !Q<5;&q&!++AvT!VtAv(ax ryyGAq4D_4D1D/E$FK[OI\$\]^<A$KHqF1QT7AaajM2HE%4L FGE jjC$B BCGg bv{###A:FAqDF|,F F?dWnGEQJEFF+A: 4<!%4LF5DMG(1d4j=)91eTJNAud w{" D1H%-3DF^Q->FD$q&>*+/a+?D$Q(%&F46N !%Qq$u+~%6!T$Z-8H!AuPTuH+W]^c_cWd eu2>>&$-!*;T%4[O=[\]  %'tD! w|  }A  wB  Cqr6!9q=T!WP_E_F1IfQi/ell  C  C8ET?+ "

288Cu4F+GPUQUY]^dejfj^kYkIk lu 88E$(O,E$(O0DQ0N+,d7dQh'()-tax.>)?dD1H%& zd4!8n:19"-a4;.?E%4LRVYZRZ"[5$< *.tAvtAv.>)?d1fd1f%&+146462B+CQQ'( xxd1f&#eDFm*<Q*F
 z6%1d46l?);<q@%Q-OQRSTVZ[\V\S\Q]]]5a=(1d1f95 *!AtET{N*;QetdSOAuUd| ?T!VD 1>4:>DdO D&a"5 Dvd| DF4AID zdQhax88E$q&M*c%Q-.@CF.J zqDz2Qq$wZ?? 5a=(1QQY<7 5[6!Q<'E5!E17bC%K--"BGGBrEBrEM*CGRWWR"W5EF6$DBJ"$D19BKK-0 A:ud#tU#D 4%<A:FF299Qa4;6G(H1TRWSW[>(YZ[E a4;/qETE{E%4LQQuA: F46N3F46N741d74qw>?TC!T'
O4s1T7|CeK,-()#D.tD ^ccfgmcn]opXYQF1Ivay6!945GSppyy1h/014299Q)* XqL4$;&AD&04;>?HSV,-"++hs6{>S2TAA: FF299Q1(9:;E!8tt| EbR wwt}$$$wwv$&&&6Q;wwqzX%%%2;;q>"""yy~~a AI---wwq!}(RWWQ]h-FFFqyTRZZh%????q&!##C IJ Ch qs   "$o=(p6&pc                 6   t         rS| |cxk\  rdkD  sJ  J d|cxk  r|cxk  rdk  sJ  J d|cxk  rdcxk  r|k  sJ  J t        j                  |      rJ ||k  r||z  }n'||k  rt        || z  |      }nt        || z  ||z        }t         r|dkD  sJ |S )zU
    This function updates the trust region radius according to RATIO and DNORM.
    r   r   )r   r   r=   r   )delta_indnormeta1eta2gamma1gamma2ratior$   s           r2   trradri     s     5$1$$$$$D$D$1$$$$$6&A&&&&&& 88E?"" } 
$FX%u-FX%v~6( qyyLr4   )__doc__numpyr   numpy.typingtypingnptcommon.constsr   r   r   r   common.powalgr   r	   common.linalgr
   r   r   r   r   r3   NDArrayr   r   ri    r4   r2   <module>rt      sH      < < 4 D D`DE$S[[ E$ E$P
0r4   