
    (phjZ                         S r SSKrSSKJr  SSKJr  SSKJr  SSK	J
r
  SSK	Jr  SS	KJr  SS
KJr  S rS rS rS rS rSS jrS rS r SS jr  SS jrg)a[  Revised simplex method for linear programming

The *revised simplex* method uses the method described in [1]_, except
that a factorization [2]_ of the basis matrix, rather than its inverse,
is efficiently maintained and used to solve the linear systems at each
iteration of the algorithm.

.. versionadded:: 1.3.0

References
----------
.. [1] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
           programming." Athena Scientific 1 (1997): 997.
.. [2] Bartels, Richard H. "A stabilization of the simplex method."
            Journal in  Numerische Mathematik 16.5 (1971): 414-434.

    N)LinAlgError)solve   )_check_unknown_options)LU)BGLU)
_postsolve)OptimizeResultc                 P   U R                   u  pSn[        XX&5      u  ppnnUS:X  a  UR                  U5      nSnUXUUUU4$ UnSn[        XUXUXVUXU
UU5      u  npnUR                  U5      nUS:X  a  UU:  a  Sn[        R
                  " U[        S9nXU:      H  nU SS2U4   n [        R                  " [        UU 5      5      n[        R                  " USS2U4   5      n[        R
                  " U[        S9nSUXU:     '   [        R                  " U5      S   n[        R                  " USS2SU24   UU4   5      nUU   nUUU4   U:  a  SUU'   M  UXU:H  '   M     U USU24   n UU   nUSU nU R                   S   nUXUUUU4$ ! [         a    Sn GM  f = f)aS  
The purpose of phase one is to find an initial basic feasible solution
(BFS) to the original problem.

Generates an auxiliary problem with a trivial BFS and an objective that
minimizes infeasibility of the original problem. Solves the auxiliary
problem using the main simplex routine (phase two). This either yields
a BFS to the original problem or determines that the original problem is
infeasible. If feasible, phase one detects redundant rows in the original
constraint matrix and removes them, then chooses additional indices as
necessary to complete a basis/BFS for the original problem.
r         dtypeNF   )shape_generate_auxiliary_problemdot
_phase_twonponesboolabsr   argmaxwherer   )Abx0callbackpostsolve_argsmaxitertoldisp	maxupdatemastpivotmnstatuscbasisxresidualiter_kphase_one_n	keep_rowsbasis_columnBbasis_finderpertinent_roweligible_columnseligible_column_indicesindexnew_basis_columns                                M/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_linprog_rs.py
_phase_oner9      s    77DAF !<A" JA!Av{558%Ax77 KF)!5*8*1*35*0+	 ?Auf uuQxH{x#~
 &Iqj)ahK	66%1+.LIIl1l?&CDM!wwq512U19-.&(hh/?&@&C#IIl1bqb51,.>>@ AE6u=M+;;<sB+0	-(/?|+, *& 	
)RaR-A)E	"1A	
Ae8VV33  	F	s   +B2FFF%$F%c                    U R                   u  p#[        R                  " X#-   5      n[        R                  " [	        U5      [
        S9nSXQ'   XE)    nXfU:     n[        R                  " X"45      nU SS2U4   USS2S[	        U5      24'   UR                  S:  aI  [        R                  R                  USS2S[	        U5      24   5      [	        U5      :  a  [        S5      eSn[        U5       Hr  n	[        R                  R                  U5      SU[	        U5      -
   n
U SS2U
4   USS2[	        U5      S24'   [        R                  R                  U5      nX:X  d  Mr    O   [        R                  " UW
45      $ )z
Called when the auxiliary problem terminates with artificial columns in
the basis, which must be removed and replaced with non-artificial
columns. Finds additional columns that do not make the matrix singular.
r   r   Nr   zBasis has dependent columns)r   r   arangezeroslenr   sizelinalgmatrix_rank	Exceptionrangerandompermutationconcatenate)r   r*   r&   r'   abloptionsr1   ranki	new_basiss              r8   _get_more_basis_columnsrL   e   sG    77DA 			!#A	#a&	%BBIfGk"G 	!A1e8Aa3u:o

QII!!!A{E
{N"34s5zA566D1XII))'2=Ac%jLA	alO!SZ[.yy$$Q'9  >>5),--    c                    SnU R                   u  pVUb  UnO[        R                  " U5      nXU-  -
  nXS:     * XS:  '   XS:     * XS:  '   XS:  ==   S-  ss'   Uc  [        R                  " U5      n	O[        R                  " X:  5      S   n	[        R                  " [        R
                  " U5      U:  5      S   n
[        U	5      S:X  a5  [        U
5      U::  a&  [        R                  " U5      n[        X
5      n
XXXt4$ [        U	5      U[        U
5      -
  :  d  [        R                  " US:  5      (       a  [        R                  " U5      nSnXXXt4$ [        X5      u  p[        R                  " X5      n[        R                  " [        R                  " X5      5      n[        R                  " X5      nUU   nUU   nU	[        R                  " [        R                  " X5      5         n[        U5      nU[        R                  " U5      -   n[        R                  " UU45      n[        R                  " UU45      n[        R                  " U [        R                  " UU45      45      n SU UU4'   [        R                  " U[        R                  " U5      45      nUU   U UU4   -  UU'   [        R                  " UU-   5      nSUU'   [        R                  " U
U45      n
[        X
5      n
XXXt4$ )aI  
Modifies original problem to create an auxiliary problem with a trivial
initial basic feasible solution and an objective that minimizes
infeasibility in the original problem.

Conceptually, this is done by stacking an identity matrix on the right of
the original constraint matrix, adding artificial variables to correspond
with each of these new columns, and generating a cost vector that is all
zeros except for ones corresponding with each of the new variables.

A initial basic feasible solution is trivial: all variables are zero
except for the artificial variables, which are set equal to the
corresponding element of the right hand side `b`.

Running the simplex method on this auxiliary problem drives all of the
artificial variables - and thus the cost - to zero if the original problem
is feasible. The original problem is declared infeasible otherwise.

Much of the complexity below is to improve efficiency by using singleton
columns in the original problem where possible, thus generating artificial
variables only as necessary, and using an initial 'guess' basic feasible
solution.
r   r   r   )r   r   r<   r;   r   r   r=   rL   any_select_singleton_columnsisinlogical_notlogical_andrE   hstack)r   r   r   r!   r(   r&   r'   r+   rnonzero_constraintsr*   r)   colsrowsi_tofixi_notinbasisi_fix_without_auxarowsn_auxacolsbasis_ngbasis_ng_rowss                         r8   r   r      s   0 F77DA	~HHQK	aCAa%yA!eHa%yA!eH!eHNH 
z iil hhqw/2 HHRVVAY_%a(E
1$UqHHQK'1Qq((
!
"QU^
3
&&Q--HHQKQq(( +10JD ggd0G >>"''$"67Lw=!"D!"D   "(; B!D EEJE		%  E~~tUm,HNND%=1M 			1bhh5z*+,AAeUlO 	288E?+,AM"1]H%<#==AhK 	AAeH
 NNE8,-E#A-E1$$rM   c                    [         R                  " [         R                  " [         R                  " U 5      S:g  SS9S:H  5      S   nU SS2U4   n[         R                  " [        U5      [        S9n[         R                  " U5      u  pVXTU'   XU4   X   -  S:  nX'   SSS2   nXG   SSS2   n[         R                  " USS9u  pX)   U4$ )	aD  
Finds singleton columns for which the singleton entry is of the same sign
as the right-hand side; these columns are eligible for inclusion in an
initial basis. Determines the rows in which the singleton entries are
located. For each of these rows, returns the indices of the one singleton
column and its corresponding row.
r   axisr   Nr   rO   T)return_index)r   nonzerosumr   r<   r=   intunique)
r   r   column_indicescolumnsrow_indicesnonzero_rowsnonzero_columns	same_signunique_row_indicesfirst_columnss
             r8   rQ   rQ      s     ZZrvvayA~A >! CDQGN>!"G((3~.c:K$&JJw$7!L#/  ~-.q~=BI#.tt4N(2.K )+		+?C)E%(*<<<rM   c                 Z    [         R                  " [         R                  " U 5      U:  SS9$ )z[
Returns logical array indicating the locations of rows with at least
one nonzero element.
r   rc   )r   rP   r   )r   r!   s     r8   _find_nonzero_rowsrs     s!    
 66"&&)c/**rM   c                 ~    UR                  5       S:X  a  X!)    [        R                  " U 5         $ X!)    X* :     S   $ )z
Selects a pivot to enter the basis. Currently Bland's rule - the smallest
index that has a negative reduced cost - is the default.
mrcr   )lowerr   argmin)c_hatrG   rF   ruler!   s        r8   _select_enter_pivotrz     sB    
 zz|uvbii&''vedl#A&&rM   c           
         US-  (       d  SOSnU(       a  [        SSSSS5        S	n [        R                  " U5      n[        UR	                  XU[        R
                  R                  U5      U5      5        g! [         a    S
n NIf = f)z9
Print indicators of optimization status to the console.
   TFPhase	IterationzMinimum Slack      zConstraint ResidualzObjective          z+{0:<6}{1:<10}{2:<20.13}{3:<20.13}{4:<20.13}NAN)printr   min
ValueErrorformatr?   norm)phase	iterationslackconfunheaderfmts          r8   _display_iterr   "  s     #RTUFg###		% 8Cu 
#**UubiinnS.A3
GH  s   A9 9BBc                     U b  SnUS U  nOSnUn[        UU5      u  ppUb  [        XUXUSUSSS.
5      nU" U5        U(       a  [        XtXU
5        g g )Nr   r   F )
r+   r   r   r   nitr   completer(   messagesuccess)r	   r
   r   )r.   r+   r   r(   r   r"   r   r   x_postsolvex_or   r   r   ress                 r8   _display_and_callbackr   8  s~    o%k&46Ce 3U%(',%(.2).	0 1
 	eC8 rM   c           
         UR                   u  pSn[        R                  " U5      n[        R                  " U5      nU	(       a  [        XX5      nO[	        X5      n[        X5       GH;  nU(       d  Ub  [        XUUXU5        [        R                  " [        U5      [        S9nSUU'   X#   nX   n UR                  USS9nU UR                  U5      -
  nUU)    n[        R                  " UU* :  5      (       a    O[        UUUXS9nUR                  USS2U4   5      nUU:  n[        R                  " U5      (       d  S	n  OUU   UU   -  n[        R                   " U5      nUU   nX#   UU-  -
  X#'   UUU'   UR#                  UU   U   U5        UR$                  nGM>     US-  nSnU(       d  Ub  [        XUUXU5        X#UU4$ ! [         a    Sn   M  f = f)
aO  
The heart of the simplex method. Beginning with a basic feasible solution,
moves to adjacent basic feasible solutions successively lower reduced cost.
Terminates when there are no basic feasible solutions with lower reduced
cost or if the problem is determined to be unbounded.

This implementation follows the revised simplex method based on LU
decomposition. Rather than maintaining a tableau or an inverse of the
basis matrix, we keep a factorization of the basis matrix that allows
efficient solution of linear systems while avoiding stability issues
associated with inverted matrices.
r   Nr   r   T)
transposedr   )ry   r!      )r   r   r;   r   r   rB   r   r<   r=   r   r   r   r   allrz   rP   rw   updater   )r)   r   r+   r   r   r   r    r!   r"   r#   r$   r%   r   r.   r&   r'   r(   rF   abr1   rG   xbcbvrx   jurJ   thlth_stars                                  r8   r   r   N  s    77DAF
		!A	1By'qH9.	8'!+.&"+8= XXc!fD)1TT	t,A AEE!Hrc
 66%C4-  r15BGGAadGGvvayyFU1Q4ZIIbMQ%tgai!	Aq1CCY /d 	Q	8'!+.&"+8= ""U  	F	s   4GGGc                 ,   [        U5        / SQnUR                  S:X  a'  [        R                  " U R                  5      SUS   S4$ [        X#XEUXxXX5      u  nnp#nnnUS:X  a  [        XUUUUXxU	XUU5      u  nnnnUUUU   R                  UU5      U4$ )a  
Solve the following linear programming problem via a two-phase
revised simplex algorithm.::

    minimize:     c @ x

    subject to:  A @ x == b
                 0 <= x < oo

User-facing documentation is in _linprog_doc.py.

Parameters
----------
c : 1-D array
    Coefficients of the linear objective function to be minimized.
c0 : float
    Constant term in objective function due to fixed (and eliminated)
    variables. (Currently unused.)
A : 2-D array
    2-D array which, when matrix-multiplied by ``x``, gives the values of
    the equality constraints at ``x``.
b : 1-D array
    1-D array of values representing the RHS of each equality constraint
    (row) in ``A_eq``.
x0 : 1-D array, optional
    Starting values of the independent variables, which will be refined by
    the optimization algorithm. For the revised simplex method, these must
    correspond with a basic feasible solution.
callback : callable, optional
    If a callback function is provided, it will be called within each
    iteration of the algorithm. The callback function must accept a single
    `scipy.optimize.OptimizeResult` consisting of the following fields:

        x : 1-D array
            Current solution vector.
        fun : float
            Current value of the objective function ``c @ x``.
        success : bool
            True only when an algorithm has completed successfully,
            so this is always False as the callback function is called
            only while the algorithm is still iterating.
        slack : 1-D array
            The values of the slack variables. Each slack variable
            corresponds to an inequality constraint. If the slack is zero,
            the corresponding constraint is active.
        con : 1-D array
            The (nominally zero) residuals of the equality constraints,
            that is, ``b - A_eq @ x``.
        phase : int
            The phase of the algorithm being executed.
        status : int
            For revised simplex, this is always 0 because if a different
            status is detected, the algorithm terminates.
        nit : int
            The number of iterations performed.
        message : str
            A string descriptor of the exit status of the optimization.
postsolve_args : tuple
    Data needed by _postsolve to convert the solution to the standard-form
    problem into the solution to the original problem.

Options
-------
maxiter : int
   The maximum number of iterations to perform in either phase.
tol : float
    The tolerance which determines when a solution is "close enough" to
    zero in Phase 1 to be considered a basic feasible solution or close
    enough to positive to serve as an optimal solution.
disp : bool
    Set to ``True`` if indicators of optimization status are to be printed
    to the console each iteration.
maxupdate : int
    The maximum number of updates performed on the LU factorization.
    After this many updates is reached, the basis matrix is factorized
    from scratch.
mast : bool
    Minimize Amortized Solve Time. If enabled, the average time to solve
    a linear system using the basis factorization is measured. Typically,
    the average solve time will decrease with each successive solve after
    initial factorization, as factorization takes much more time than the
    solve operation (and updates). Eventually, however, the updated
    factorization becomes sufficiently complex that the average solve time
    begins to increase. When this is detected, the basis is refactorized
    from scratch. Enable this option to maximize speed at the risk of
    nondeterministic behavior. Ignored if ``maxupdate`` is 0.
pivot : "mrc" or "bland"
    Pivot rule: Minimum Reduced Cost (default) or Bland's rule. Choose
    Bland's rule if iteration limit is reached and cycling is suspected.
unknown_options : dict
    Optional arguments not used by this particular solver. If
    `unknown_options` is non-empty a warning is issued listing all
    unused options.

Returns
-------
x : 1-D array
    Solution vector.
status : int
    An integer representing the exit status of the optimization::

     0 : Optimization terminated successfully
     1 : Iteration limit reached
     2 : Problem appears to be infeasible
     3 : Problem appears to be unbounded
     4 : Numerical difficulties encountered
     5 : No constraints; turn presolve on
     6 : Guess x0 cannot be converted to a basic feasible solution

message : str
    A string descriptor of the exit status of the optimization.
iteration : int
    The number of iterations taken to solve the problem.
)z%Optimization terminated successfully.zIteration limit reached.aS  The problem appears infeasible, as the phase one auxiliary problem terminated successfully with a residual of {0:.1e}, greater than the tolerance {1} required for the solution to be considered feasible. Consider increasing the tolerance to be greater than {0:.1e}. If this tolerance is unacceptably large, the problem is likely infeasible.zThe problem is unbounded, as the simplex algorithm found a basic feasible solution from which there is a direction with negative reduced cost in which all decision variables increase.zLNumerical difficulties encountered; consider trying method='interior-point'.zKProblems with no constraints are trivially solved; please turn presolve on.z?The guess x0 cannot be converted to a basic feasible solution. r      )r   r>   r   r<   r   r9   r   r   )r)   c0r   r   r   r   r   r    r!   r"   r#   r$   r%   unknown_optionsmessagesr+   r*   r,   r(   r   s                       r8   _linprog_rsr     s    n ?+H( 	vv{xx !Xa[!33 	1~$	? 0AuaHfi {&0q%1?18t1:%1:	'<#5&) fhv&--h<iGGrM   )bland-q=)r   N)i  r   F
   Fru   )__doc__numpyr   numpy.linalgr   scipy.linalgr   	_optimizer   _bglu_denser   r   _linprog_utilr	   r
   r9   rL   r   rQ   rs   rz   r   r   r   r    rM   r8   <module>r      sp   &  $  -  % % %C4L .Fd%N=@+'I,9. AEP#h /405[HrM   