
    (ph`                     r    S r SSKrSSKJr  SSKJrJrJr  SSK	J
r
  SS jrSS jrSS	 jr SS
 jr SS jrg)a  Simplex method for  linear programming

The *simplex* method uses a traditional, full-tableau implementation of
Dantzig's simplex algorithm [1]_, [2]_ (*not* the Nelder-Mead simplex).
This algorithm is included for backwards compatibility and educational
purposes.

    .. versionadded:: 0.15.0

Warnings
--------

The simplex method may encounter numerical difficulties when pivot
values are close to the specified tolerance. If encountered try
remove any redundant constraints, change the pivot strategy to Bland's
rule or increase the tolerance value.

Alternatively, more robust methods maybe be used. See
:ref:`'interior-point' <optimize.linprog-interior-point>` and
:ref:`'revised simplex' <optimize.linprog-revised_simplex>`.

References
----------
.. [1] Dantzig, George B., Linear programming and extensions. Rand
       Corporation Research Study Princeton Univ. Press, Princeton, NJ,
       1963
.. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
       Mathematical Programming", McGraw-Hill, Chapter 4.
    N)warn   )OptimizeResultOptimizeWarning_check_unknown_options)
_postsolvec                    [         R                  R                  U SSS24   U* :  U SSS24   SS9nUR                  5       S:X  a  S[         R                  4$ U(       aP  S[         R
                  " [         R                  " [         R                  " UR                  5      5      5      S   S   4$ S[         R                  R                  X3R                  5       :H  5      S   S   4$ )a  
Given a linear programming simplex tableau, determine the column
of the variable to enter the basis.

Parameters
----------
T : 2-D array
    A 2-D array representing the simplex tableau, T, corresponding to the
    linear programming problem. It should have the form:

    [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
     [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
     .
     .
     .
     [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
     [c[0],   c[1], ...,   c[n_total],    0]]

    for a Phase 2 problem, or the form:

    [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
     [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
     .
     .
     .
     [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
     [c[0],   c[1], ...,   c[n_total],   0],
     [c'[0],  c'[1], ...,  c'[n_total],  0]]

     for a Phase 1 problem (a problem in which a basic feasible solution is
     sought prior to maximizing the actual objective. ``T`` is modified in
     place by ``_solve_simplex``.
tol : float
    Elements in the objective row larger than -tol will not be considered
    for pivoting. Nominally this value is zero, but numerical issues
    cause a tolerance about zero to be necessary.
bland : bool
    If True, use Bland's rule for selection of the column (select the
    first column with a negative coefficient in the objective row,
    regardless of magnitude).

Returns
-------
status: bool
    True if a suitable pivot column was found, otherwise False.
    A return of False indicates that the linear programming simplex
    algorithm is complete.
col: int
    The index of the column of the pivot element.
    If status is False, col will be returned as nan.
NFcopyr   T)
npmamasked_wherecountnannonzerological_not
atleast_1dmaskmin)Ttolblandr   s       R/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_linprog_simplex.py
_pivot_colr   %   s    h 
		Ab#2#gJ3$."crc'
		GB	xxzQbff}RZZr}}RWW/E FGJ1MMMrVVX~.q1!444    c                    US:X  a  SnOSn[         R                  R                  U SU* 2U4   U:*  U SU* 2U4   SS9nUR                  5       S:X  a  S[         R                  4$ [         R                  R                  U SU* 2U4   U:*  U SU* 2S4   SS9nX-  n	[         R                  R                  XR                  5       :H  5      S   n
U(       a/  SU
[         R                  " [         R                  " X5      5         4$ SU
S   4$ )	a  
Given a linear programming simplex tableau, determine the row for the
pivot operation.

Parameters
----------
T : 2-D array
    A 2-D array representing the simplex tableau, T, corresponding to the
    linear programming problem. It should have the form:

    [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
     [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
     .
     .
     .
     [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
     [c[0],   c[1], ...,   c[n_total],    0]]

    for a Phase 2 problem, or the form:

    [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
     [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
     .
     .
     .
     [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
     [c[0],   c[1], ...,   c[n_total],   0],
     [c'[0],  c'[1], ...,  c'[n_total],  0]]

     for a Phase 1 problem (a Problem in which a basic feasible solution is
     sought prior to maximizing the actual objective. ``T`` is modified in
     place by ``_solve_simplex``.
basis : array
    A list of the current basic variables.
pivcol : int
    The index of the pivot column.
phase : int
    The phase of the simplex algorithm (1 or 2).
tol : float
    Elements in the pivot column smaller than tol will not be considered
    for pivoting. Nominally this value is zero, but numerical issues
    cause a tolerance about zero to be necessary.
bland : bool
    If True, use Bland's rule for selection of the row (if more than one
    row can be used, choose the one with the lowest variable index).

Returns
-------
status: bool
    True if a suitable pivot row was found, otherwise False. A return
    of False indicates that the linear programming problem is unbounded.
row: int
    The index of the row of the pivot element. If status is False, row
    will be returned as nan.
r      NFr   r   r
   T)	r   r   r   r   r   r   r   argmintake)r   basispivcolphaser   r   kr   mbqmin_rowss              r   
_pivot_rowr(   b   s   p z			Acrc6kNc11SqbS&[>		NB	xxzQbff}			Acrc6kNc11SqbS"W:E		JB
Auu}}Q%%'\*1-HXbii(@ABBB!r   c                    X1U'   XU4   nX   U-  X'   [        U R                  S   5       H  nXb:w  d  M
  X   X   XU4   -  -
  X'   M     [        R                  " XTSSS9(       a  SUS SUS S3n[	        U[
        SS	9  g
g
)aY  
Pivot the simplex tableau inplace on the element given by (pivrow, pivol).
The entering variable corresponds to the column given by pivcol forcing
the variable basis[pivrow] to leave the basis.

Parameters
----------
T : 2-D array
    A 2-D array representing the simplex tableau, T, corresponding to the
    linear programming problem. It should have the form:

    [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
     [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
     .
     .
     .
     [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
     [c[0],   c[1], ...,   c[n_total],    0]]

    for a Phase 2 problem, or the form:

    [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
     [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
     .
     .
     .
     [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
     [c[0],   c[1], ...,   c[n_total],   0],
     [c'[0],  c'[1], ...,  c'[n_total],  0]]

     for a Phase 1 problem (a problem in which a basic feasible solution is
     sought prior to maximizing the actual objective. ``T`` is modified in
     place by ``_solve_simplex``.
basis : 1-D array
    An array of the indices of the basic variables, such that basis[i]
    contains the column corresponding to the basic variable for row i.
    Basis is modified in place by _apply_pivot.
pivrow : int
    Row index of the pivot.
pivcol : int
    Column index of the pivot.
r   g     @)atolrtolz.The pivot operation produces a pivot value of:z .1ez=, which is only slightly greater than the specified tolerancez. This may lead to issues regarding the numerical stability of the simplex method. Removing redundant constraints, changing the pivot strategy via Bland's rule or increasing the tolerance may help reduce the issue.   )
stacklevelN)rangeshaper   iscloser   r   )r   r!   pivrowr"   r   pivvalirowmessages           r   _apply_pivotr5      s    V &Mv~F	F"AIaggaj!>g	AFlO ;;AG "
 
zz&AC0<VDM JDz "%% 	 	Wo!4 1r   c
                    U	n
SnSnSnUS:X  a  U R                   S   S-
  nO$US:X  a  U R                   S   S-
  nO[        S5      eUS:X  a  [        UR                  5       Vs/ s H  nX/   U R                   S   S-
  :  d  M  UPM!     sn Hm  n[        U R                   S   S-
  5       Vs/ s H  n[	        U UU4   5      U:  d  M  UPM     nn[        U5      S:  d  MU  US   n[        XUUU5        U
S-  n
Mo     [        USU 5      S:X  a4  [        R                  " U R                   S   S-
  [        R                  S9nOL[        R                  " [        U R                   S   S-
  [        USU 5      S-   5      [        R                  S9nU(       d  [        XU5      u  nnU(       d%  [        R                  n[        R                  nSnS	nO[        XUXvU5      u  nnU(       d  S
nS	nUbT  SUSS& U SU2S4   UUSU '   USU n[        UU5      u  nnnn[        UUUUUUU
US:H  =(       a    UUUS.
5      nU" U5        U(       d  X:  a  SnS	nO[        XUUU5        U
S-  n
U(       d  M  X4$ s  snf s  snf )a,  
Solve a linear programming problem in "standard form" using the Simplex
Method. Linear Programming is intended to solve the following problem form:

Minimize::

    c @ x

Subject to::

    A @ x == b
        x >= 0

Parameters
----------
T : 2-D array
    A 2-D array representing the simplex tableau, T, corresponding to the
    linear programming problem. It should have the form:

    [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
     [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
     .
     .
     .
     [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
     [c[0],   c[1], ...,   c[n_total],    0]]

    for a Phase 2 problem, or the form:

    [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
     [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
     .
     .
     .
     [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
     [c[0],   c[1], ...,   c[n_total],   0],
     [c'[0],  c'[1], ...,  c'[n_total],  0]]

     for a Phase 1 problem (a problem in which a basic feasible solution is
     sought prior to maximizing the actual objective. ``T`` is modified in
     place by ``_solve_simplex``.
n : int
    The number of true variables in the problem.
basis : 1-D array
    An array of the indices of the basic variables, such that basis[i]
    contains the column corresponding to the basic variable for row i.
    Basis is modified in place by _solve_simplex
callback : callable, optional
    If a callback function is provided, it will be called within each
    iteration of the algorithm. The callback must accept a
    `scipy.optimize.OptimizeResult` consisting of the following fields:

        x : 1-D array
            Current solution vector
        fun : float
            Current value of the objective function
        success : bool
            True only when a phase has completed successfully. This
            will be False for most iterations.
        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 optimization being executed. In phase 1 a basic
            feasible solution is sought and the T has an additional row
            representing an alternate objective function.
        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 : Serious numerical difficulties encountered

        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.
maxiter : int
    The maximum number of iterations to perform before aborting the
    optimization.
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.
phase : int
    The phase of the optimization being executed. In phase 1 a basic
    feasible solution is sought and the T has an additional row
    representing an alternate objective function.
bland : bool
    If True, choose pivots using Bland's rule [3]_. In problems which
    fail to converge due to cycling, using Bland's rule can provide
    convergence at the expense of a less optimal path about the simplex.
nit0 : int
    The initial iteration number used to keep an accurate iteration total
    in a two-phase problem.

Returns
-------
nit : int
    The number of iterations. Used to keep an accurate iteration total
    in the two-phase problem.
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 : Serious numerical difficulties encountered

r    Fr   r   z1Argument 'phase' to _solve_simplex must be 1 or 2N)dtypeT   r
   )
xfunslackconstatusr4   nitsuccessr#   complete)r/   
ValueErrorr.   sizeabslenr5   r   emptyfloat64maxr   r   r(   r   r   )r   nr!   callbackpostsolve_argsmaxiterr   r#   r   nit0r?   r>   r4   rA   mrowr1   colnon_zero_rowr"   solutionpivcol_foundpivrow_foundr:   r;   r<   r=   ress                               r   _solve_simplexrV      s   v CFGHzGGAJqL	!GGAJqLLMMz ',EJJ&7 7&7s*qwwqzA~5 &7 7F+0a+@ :+@C"1VS[>2S8  +@L :< 1$%aQvvs;q7 5!9~88AGGAJN"**=88C
QE"1I0BC"$**. )!%8fVVFVVFFH $.aE#R L&HQK"#BQBF)HU2AY!A!+>"AsE3 ! "!Q;38$" C SM~Qvvs;qW hX ;w7:s   #I4I4,I9I9c
                    [        U
5        SnSSSSSS.nUR                  u  p[        R                  " US5      nX/==   S-  ss'   X?==   S-  ss'   [        R                  " U5      U-   nUR                  5       n[        R                  " U[        R                  " U5      US	S	2[        R                  4   45      n[        R                  " U [        R                  " U5      U45      nUR                  SS
9* nSUU'   [        R                  " UUU45      n[        UUUUUXgSU	S9	u  nnUn[        US   5      U:  a$  US	S2S	S	24   n[        R                  " UUS5      nO*SnS[        US   5      S SU S[        US   5      S S3X'   US:X  a  [        UUUUUXgSU	US9
u  nn[        R                  " X-   5      nUS	U2S4   UUS	U '   US	U nUXU   [        U5      4$ )a  
Minimize a linear objective function subject to linear equality and
non-negativity constraints using the two phase simplex method.
Linear programming is intended to solve problems of the following form:

Minimize::

    c @ x

Subject to::

    A @ x == b
        x >= 0

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. (Purely for display.)
A : 2-D array
    2-D array such that ``A @ x``, gives the values of the equality
    constraints at ``x``.
b : 1-D array
    1-D array of values representing the right hand side of each equality
    constraint (row) in ``A``.
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
        success : bool
            True when an algorithm has completed successfully.
        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
            An integer representing the status of the optimization::

                 0 : Algorithm proceeding nominally
                 1 : Iteration limit reached
                 2 : Problem appears to be infeasible
                 3 : Problem appears to be unbounded
                 4 : Serious numerical difficulties encountered
        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.
disp : bool
    If True, print exit status message to sys.stdout
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.
bland : bool
    If True, use Bland's anti-cycling rule [3]_ to choose pivots to
    prevent cycling. If False, choose pivots which should lead to a
    converged solution more quickly. The latter method is subject to
    cycling (non-convergence) in rare instances.
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 : Serious numerical difficulties encountered

message : str
    A string descriptor of the exit status of the optimization.
iteration : int
    The number of iterations taken to solve the problem.

References
----------
.. [1] Dantzig, George B., Linear programming and extensions. Rand
       Corporation Research Study Princeton Univ. Press, Princeton, NJ,
       1963
.. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
       Mathematical Programming", McGraw-Hill, Chapter 4.
.. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
       Mathematics of Operations Research (2), 1977: pp. 103-107.


Notes
-----
The expected problem formulation differs between the top level ``linprog``
module and the method specific solvers. The method specific solvers expect a
problem in standard form:

Minimize::

    c @ x

Subject to::

    A @ x == b
        x >= 0

Whereas the top level ``linprog`` module expects a problem of form:

Minimize::

    c @ x

Subject to::

    A_ub @ x <= b_ub
    A_eq @ x == b_eq
     lb <= x <= ub

where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.

The original problem contains equality, upper-bound and variable constraints
whereas the method specific solver requires equality constraints and
variable non-negativity.

``linprog`` module converts the original problem to standard form by
converting the simple bounds to upper bound constraints, introducing
non-negative slack variables for inequality constraints, and expressing
unbounded variables as the difference between two non-negative variables.
r   z%Optimization terminated successfully.zIteration limit reached.z>Optimization failed. Unable to find a feasible starting point.z9Optimization failed. The problem appears to be unbounded.z1Optimization failed. Singular matrix encountered.)r   r   r   r9      r
   N)axisr   )rJ   rK   rL   r   r#   r   )r
   r
   r   zmPhase 1 of the simplex method failed to find a feasible solution. The pseudo-objective function evaluates to z.1ez) which exceeds the required tolerance of z for a solution to be considered 'close enough' to zero to be a basic solution. Consider increasing the tolerance to be greater than zH. If this tolerance is unacceptably large the problem may be infeasible.)rJ   rK   rL   r   r#   r   rM   )r   r/   r   lessaranger   hstackeyenewaxiszerossumvstackrV   rD   deleteint)cc0AbrJ   rK   rL   r   dispr   unknown_optionsr>   messagesrI   rN   is_negative_constraintavr!   row_constraintsrow_objectiverow_pseudo_objectiver   nit1nit2rR   r:   s                             r   _linprog_simplexrr     s,   v ?+F:-&NFHH 77DA  WWQ]## 
1	BGGIE iiBFF1IqBJJ/? @AOIIq"((1+r23M+//Q/77 
		?M3GHIA!!Q1?*1!(-$LD& D
1V9~crc1fIIIaQ D1V9~c" #77:e <D 1V9~c" # 	 {%aEH5C.5a,1(f xxHBQBF)HU2AY!Afv&D	11r   )&.>F)rs   )  rs   r   Fr   )rt   rs   FF)__doc__numpyr   warningsr   	_optimizer   r   r   _linprog_utilr   r   r(   r5   rV   rr    r   r   <module>r{      sI   <   N N %:5zDN<5@ GHK^ @Ea2r   