
    wg                     $   d Z ddlmZ ddlmZ ddlmZmZmZ ddl	m
Z
 ddlmZ ddlm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  G d de      Z G d de      Zd Zd Zd dZd!dZ d"dZ!d#dZ"d Z#d Z$d Z%d Z&d Z'd Z(d$dZ)d$dZ*y)%a  Tools for optimizing a linear function for a given simplex.

For the linear objective function ``f`` with linear constraints
expressed using `Le`, `Ge` or `Eq` can be found with ``lpmin`` or
``lpmax``. The symbols are **unbounded** unless specifically
constrained.

As an alternative, the matrices describing the objective and the
constraints, and an optional list of bounds can be passed to
``linprog`` which will solve for the minimization of ``C*x``
under constraints ``A*x <= b`` and/or ``Aeq*x = beq``, and
individual bounds for variables given as ``(lo, hi)``. The values
returned are **nonnegative** unless bounds are provided that
indicate otherwise.

Errors that might be raised are UnboundedLPError when there is no
finite solution for the system or InfeasibleLPError when the
constraints represent impossible conditions (i.e. a non-existant
 simplex).

Here is a simple 1-D system: minimize `x` given that ``x >= 1``.

    >>> from sympy.solvers.simplex import lpmin, linprog
    >>> from sympy.abc import x

    The function and a list with the constraint is passed directly
    to `lpmin`:

    >>> lpmin(x, [x >= 1])
    (1, {x: 1})

    For `linprog` the matrix for the objective is `[1]` and the
    uivariate constraint can be passed as a bound with None acting
    as infinity:

    >>> linprog([1], bounds=(1, None))
    (1, [1])

    Or the matrices, corresponding to ``x >= 1`` expressed as
    ``-x <= -1`` as required by the routine, can be passed:

    >>> linprog([1], [-1], [-1])
    (1, [1])

    If there is no limit for the objective, an error is raised.
    In this case there is a valid region of interest (simplex)
    but no limit to how small ``x`` can be:

    >>> lpmin(x, [])
    Traceback (most recent call last):
    ...
    sympy.solvers.simplex.UnboundedLPError:
    Objective function can assume arbitrarily large values!

    An error is raised if there is no possible solution:

    >>> lpmin(x,[x<=1,x>=2])
    Traceback (most recent call last):
    ...
    sympy.solvers.simplex.InfeasibleLPError:
    Inconsistent/False constraint
    )sympify)factor_terms)LeGeEq)S)Dummy)ordered)sign)Matrixzeros)linear_eq_to_matrixnumbered_symbols)
filldedentc                       e Zd ZdZy)UnboundedLPErrora  
    A linear programing problem is said to be unbounded if its objective
    function can assume arbitrarily large values.

    Example
    =======

    Suppose you want to maximize
        2x
    subject to
        x >= 0

    There's no upper limit that 2x can take.
    N__name__
__module____qualname____doc__     Z/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/solvers/simplex.pyr   r   M   s     	r   r   c                       e Zd ZdZy)InfeasibleLPErrorai  
    A linear programing problem is considered infeasible if its
    constraint set is empty. That is, if the set of all vectors
    satisfying the contraints is empty, then the problem is infeasible.

    Example
    =======

    Suppose you want to maximize
        x
    subject to
        x >= 10
        x <= 9

    No x can satisfy those constraints.
    Nr   r   r   r   r   r   `   s    " 	r   r   c                     | |ddf   | dd|f   | ||f   }}}|dk(  rt        d      | |||z  z  z
  }||z  ||ddf<   | |z  |dd|f<   d|z  |||f<   |S )a  
    The pivot element `M[i, j]` is inverted and the rest of the matrix
    modified and returned as a new matrix; original is left unmodified.

    Example
    =======

    >>> from sympy.matrices.dense import Matrix
    >>> from sympy.solvers.simplex import _pivot
    >>> from sympy import var
    >>> Matrix(3, 3, var('a:i'))
    Matrix([
    [a, b, c],
    [d, e, f],
    [g, h, i]])
    >>> _pivot(_, 1, 0)
    Matrix([
    [-a/d, -a*e/d + b, -a*f/d + c],
    [ 1/d,        e/d,        f/d],
    [-g/d,  h - e*g/d,  i - f*g/d]])
    Nr   z'Tried to pivot about zero-valued entry.   )ZeroDivisionError)MijMiMjMijAs          r   _pivotr(   u   s    , AqD'1QT7AadGCB
ax57 	7	B"s(OA3hAadGcCiAadG#gAadGHr   c                 0     t        | fd      S )Nc                 (    |    | f   z  |    fS Nr   )r"   r'   BY	pivot_cols    r   <lambda>z#_choose_pivot_row.<locals>.<lambda>   s!    adQq)|_.Dad-K r   )key)min)r'   r,   candidate_rowsr.   r-   s   `` ``r   _choose_pivot_rowr3      s     ~#KLLr   Nc                    | ||xs dgfD cg c]  }t        |       c}\  } }}|r8t        | j                   |j                  j                  |       \  }}}| ||fS | rrt        | g||gg      }	n| srt        d      t        ||gg      }	|	j                  dz
  }
|	j
                  dz
  }t        d |	D              st        t        d            t        |
      D cg c]  }d|f c}t        |      D cg c]  }d|f }}d}	 |	dd	d	f   |	dd	dd	f   } t        fd
t        j
                        D              rnt        j
                        D ]  }|   dk  s n 	 t        | j                        D cg c]  }| |f   dk  s| }}|st        t        d            t        fd|D              \  }}t        | j
                        D cg c]  }| ||f   dkD  s|   dkD  s| }}|j                         t        | |||      }||f|k(  rd}n$||f}t        |	||      }	||   |   c|<   ||<   @	 |	dd	d	f   |	dd	dd	f   } |	d	dd	f   }g }t        |
      D cg c]  }||   dk  s| }}|sn~t        fd|D              \  }}t        |      D cg c]  }| ||f   dkD  s| }}|st        t        d            t        | |||      }t        |	||      }	||   |   c|<   ||<   dg|
z  }dg|z  }t!              D ]  \  }\  }}
|dk(  rd||
<   |	d	|f   ||
<    t!        |      D ]  \  }\  }}
|dk(  rd||
<   |	|d	f   ||
<    |r)t        d ||z   D              st        t        d            |	d    ||fS c c}w c c}w c c}w c c}w c c}w c c}w c c}w )aO  Return ``(o, x, y)`` obtained from the two-phase simplex method
    using Bland's rule: ``o`` is the minimum value of primal,
    ``Cx - D``, under constraints ``Ax <= B`` (with ``x >= 0``) and
    the maximum of the dual, ``y^{T}B - D``, under constraints
    ``A^{T}*y >= C^{T}`` (with ``y >= 0``). To compute the dual of
    the system, pass `dual=True` and ``(o, y, x)`` will be returned.

    Note: the nonnegative constraints for ``x`` and ``y`` supercede
    any values of ``A`` and ``B`` that are inconsistent with that
    assumption, so if a constraint of ``x >= -1`` is represented
    in ``A`` and ``B``, no value will be obtained that is negative; if
    a constraint of ``x <= -1`` is represented, an error will be
    raised since no solution is possible.

    This routine relies on the ability of determining whether an
    expression is 0 or not. This is guaranteed if the input contains
    only Float or Rational entries. It will raise a TypeError if
    a relationship does not evaluate to True or False.

    Examples
    ========

    >>> from sympy.solvers.simplex import _simplex
    >>> from sympy import Matrix

    Consider the simple minimization of ``f = x + y + 1`` under the
    constraint that ``y + 2*x >= 4``. This is the "standard form" of
    a minimization.

    In the nonnegative quadrant, this inequality describes a area above
    a triangle with vertices at (0, 4), (0, 0) and (2, 0). The minimum
    of ``f`` occurs at (2, 0). Define A, B, C, D for the standard
    minimization:

    >>> A = Matrix([[2, 1]])
    >>> B = Matrix([4])
    >>> C = Matrix([[1, 1]])
    >>> D = Matrix([-1])

    Confirm that this is the system of interest:

    >>> from sympy.abc import x, y
    >>> X = Matrix([x, y])
    >>> (C*X - D)[0]
    x + y + 1
    >>> [i >= j for i, j in zip(A*X, B)]
    [2*x + y >= 4]

    Since `_simplex` will do a minimization for constraints given as
    ``A*x <= B``, the signs of ``A`` and ``B`` must be negated since
    the currently correspond to a greater-than inequality:

    >>> _simplex(-A, -B, C, D)
    (3, [2, 0], [1/2])

    The dual of minimizing ``f`` is maximizing ``F = c*y - d`` for
    ``a*y <= b`` where ``a``, ``b``, ``c``, ``d`` are derived from the
    transpose of the matrix representation of the standard minimization:

    >>> tr = lambda a, b, c, d: [i.T for i in (a, c, b, d)]
    >>> a, b, c, d = tr(A, B, C, D)

    This time ``a*x <= b`` is the expected inequality for the `_simplex`
    method, but to maximize ``F``, the sign of ``c`` and ``d`` must be
    changed (so that minimizing the negative will give the negative of
    the maximum of ``F``):

    >>> _simplex(a, b, -c, -d)
    (-3, [1/2], [2, 0])

    The negative of ``F`` and the min of ``f`` are the same. The dual
    point `[1/2]` is the value of ``y`` that minimized ``F = c*y - d``
    under constraints a*x <= b``:

    >>> y = Matrix(['y'])
    >>> (c*y - d)[0]
    4*y + 1
    >>> [i <= j for i, j in zip(a*y,b)]
    [2*y <= 1, y <= 1]

    In this 1-dimensional dual system, the more restrictive contraint is
    the first which limits ``y`` between 0 and 1/2 and the maximum of
    ``F`` is attained at the nonzero value, hence is ``4*(1/2) + 1 = 3``.

    In this case the values for ``x`` and ``y`` were the same when the
    dual representation was solved. This is not always the case (though
    the value of the function will be the same).

    >>> l = [[1, 1], [-1, 1], [0, 1], [-1, 0]], [5, 1, 2, -1], [[1, 1]], [-1]
    >>> A, B, C, D = [Matrix(i) for i in l]
    >>> _simplex(A, B, -C, -D)
    (-6, [3, 2], [1, 0, 0, 0])
    >>> _simplex(A, B, -C, -D, dual=True)  # [5, 0] != [3, 2]
    (-6, [1, 0, 0, 0], [5, 0])

    In both cases the function has the same value:

    >>> Matrix(C)*Matrix([3, 2]) == Matrix(C)*Matrix([5, 0])
    True

    See Also
    ========
    _lp - poses min/max problem in form compatible with _simplex
    lpmin - minimization which calls _lp
    lpmax - maximimzation which calls _lp

    References
    ==========

    .. [1] Thomas S. Ferguson, LINEAR PROGRAMMING: A Concise Introduction
           web.tecnico.ulisboa.pt/mcasquilho/acad/or/ftp/FergusonUCLA_lp.pdf

    r   zmust give A and Br   c              3   P   K   | ]  }|j                   xs |j                     y wr+   )is_Floatis_Rational.0r"   s     r   	<genexpr>z_simplex.<locals>.<genexpr>  s      6qqzz*Q]]*6s   $&z@
            Only rationals and floats are allowed.
            FTNc              3   .   K   | ]  }|   d k\    ywr   Nr   )r9   r"   r,   s     r   r:   z_simplex.<locals>.<genexpr>3  s     0Qqtqy0s   z-
                The constraint set is empty!c              3   ,   K   | ]  }|   |f  y wr+   r   r9   r"   Xs     r   r:   z_simplex.<locals>.<genexpr>C       /AaD!9/   c              3   ,   K   | ]  }|   |f  y wr+   r   r?   s     r   r:   z_simplex.<locals>.<genexpr>n  rA   rB   zX
                Objective function can assume
                arbitrarily large values!c              3   &   K   | ]	  }|d k\    ywr=   r   r8   s     r   r:   z_simplex.<locals>.<genexpr>  s     =1Q=s   z
            Oscillating system led to invalid solution.
            If you believe there was a valid solution, please
            report this as a bug.)r;   r;   )r   _simplexT
ValueErrorcolsrowsall	TypeErrorr   ranger   r1   appendr3   r(   r   	enumerate)r'   r,   CDdualr"   _odpr!   nmr#   r-   lastk_piv_colscpiv_rowsrargmaxargmin_dualvr@   s    `                      @r   rE   rE      s   d '(AqxQC%89&)9JAq!QQSSD!##qssQB/AqsAqyQQFQF#$011QF8	
A	
A6A66 
 $  
 	
 #1X&%&A!!H%q$%A%
 D
crc2gJcrc3B3hK0%-00 qvv 	Atax	   %QVV}<!!Q$!A<<#J 00 %1 2 2/h//1  %QVV}I!!Q$!!qAIIaHa3 q6T>" D!t1aOqT1Q4
!adc h crc2gJcrc3B3hKb#2#gJ $Qx4!1Q4!8A44/h//1  %Qx7!1QT7Q;A77": /- $. / / aHa31aOqT1Q4
!ad+ . VaZF&1*Kq\ &	6Aq:F1Ir1uXKN	& q\ !	6Aq9KN!R%F1I	! C=(<==
 ,% !& ' 	' fI:v{**C :4 	'%, = JJ 5 8sG   N+(N0N5N:N:&N?6N??N? OO;O	O	c                     d }| ddddf   | dddf   | dddf   | ddddf   f}|s|S t        |D cg c]
  } ||       c}      S c c}w )aE  return parts of M as matrices or lists

    Examples
    ========

    >>> from sympy import Matrix
    >>> from sympy.solvers.simplex import _abcd

    >>> m = Matrix(3, 3, range(9)); m
    Matrix([
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8]])
    >>> a, b, c, d = _abcd(m)
    >>> a
    Matrix([
    [0, 1],
    [3, 4]])
    >>> b
    Matrix([
    [2],
    [5]])
    >>> c
    Matrix([[6, 7]])
    >>> d
    Matrix([[8]])

    The matrices can be returned as compact lists, too:

    >>> L = a, b, c, d = _abcd(m, list=True); L
    ([[0, 1], [3, 4]], [2, 5], [[6, 7]], [8])
    c                 x    | j                         }t        |d         dk(  r|D  cg c]  } | d   	 c} S |S c c} w )Nr   r   )tolistlen)r"   ls     r   aslistz_abcd.<locals>.aslist  s;    HHJqt9>"#$QAaD$$ %s   7Nr;   )tuple)r!   listrf   rV   r"   s        r   _abcdri     sq    D 	
#2#ss(QssBwZ2ss7QrsBCx[8AQ'&)'(('s   Ac                 |    | |||xs dgfD cg c]  }t        |       c}\  } }}}t        | |g||gg      S c c}w )a  return Matrix([[a, b], [c, d]]) from matrices
    in Matrix or list form.

    Examples
    ========

    >>> from sympy import Matrix
    >>> from sympy.solvers.simplex import _abcd, _m
    >>> m = Matrix(3, 3, range(9))
    >>> L = _abcd(m, list=True); L
    ([[0, 1], [3, 4]], [2, 5], [[6, 7]], [8])
    >>> _abcd(m)
    (Matrix([
    [0, 1],
    [3, 4]]), Matrix([
    [2],
    [5]]), Matrix([[6, 7]]), Matrix([[8]]))
    >>> assert m == _m(*L) == _m(*_)
    r   )r   )abr[   rS   r"   s        r   _mrm     sL    ( '(AqxQC%89&)9JAq!QAq6Aq6"## :s   9c                 ~   | sdg fdg ffS t        | d      s t        |       dvrt        d      t        |  } | j                  D cg c]  }|dz
  	 c}\  }}t        |       \  }}}}|d   }d }	t        t         |	d      t        |            D 
cg c]  \  }}
|	 c}
}      }t        t         |	d	      t        |            D 
cg c]  \  }}
|	 c}
}      j                  }fd
}d } |||z  |      } |||z  |      }| |||z  |t              f| |||z  |t              ffS c c}w c c}
}w c c}
}w )a/	  return primal and dual function and constraints
    assuming that ``M = Matrix([[A, b], [c, d]])`` and the
    function ``c*x - d`` is being minimized with ``Ax >= b``
    for nonnegative values of ``x``. The dual and its
    constraints will be for maximizing `b.T*y - d` subject
    to ``A.T*y <= c.T``.

    Examples
    ========

    >>> from sympy.solvers.simplex import _primal_dual, lpmin, lpmax
    >>> from sympy import Matrix

    The following matrix represents the primal task of
    minimizing x + y + 7 for y >= x + 1 and y >= -2*x + 3.
    The dual task seeks to maximize x + 3*y + 7 with
    2*y - x <= 1 and and x + y <= 1:

    >>> M = Matrix([
    ...     [-1, 1,  1],
    ...     [ 2, 1,  3],
    ...     [ 1, 1, -7]])
    >>> p, d = _primal_dual(M)

    The minimum of the primal and maximum of the dual are the same
    (though they occur at different points):

    >>> lpmin(*p)
    (28/3, {x1: 2/3, x2: 5/3})
    >>> lpmax(*d)
    (28/3, {y1: 1/3, y2: 2/3})

    If the equivalent (but canonical) inequalities are
    desired, leave `factor=True`, otherwise the unmodified
    inequalities for M will be returned.

    >>> m = Matrix([
    ... [-3, -2,  4, -2],
    ... [ 2,  0,  0, -2],
    ... [ 0,  1, -3,  0]])

    >>> _primal_dual(m, False)  # last condition is 2*x1 >= -2
    ((x2 - 3*x3,
        [-3*x1 - 2*x2 + 4*x3 >= -2, 2*x1 >= -2]),
    (-2*y1 - 2*y2,
        [-3*y1 + 2*y2 <= 0, -2*y1 <= 1, 4*y1 <= -3]))

    >>> _primal_dual(m)  # condition now x1 >= -1
    ((x2 - 3*x3,
        [-3*x1 - 2*x2 + 4*x3 >= -2, x1 >= -1]),
    (-2*y1 - 2*y2,
        [-3*y1 + 2*y2 <= 0, -2*y1 <= 1, 4*y1 <= -3]))

    If you pass the transpose of the matrix, the primal will be
    identified as the standard minimization problem and the
    dual as the standard maximization:

    >>> _primal_dual(m.T)
    ((-2*x1 - 2*x2,
        [-3*x1 + 2*x2 >= 0, -2*x1 >= 1, 4*x1 >= -3]),
    (y2 - 3*y3,
        [-3*y1 - 2*y2 + 4*y3 <= -2, y1 <= -1]))

    A matrix must have some size or else None will be returned for
    the functions:

    >>> _primal_dual(Matrix([[1, 2]]))
    ((x1 - 2, []), (-2, []))

    >>> _primal_dual(Matrix([]))
    ((None, []), (None, []))

    References
    ==========

    .. [1] David Galvin, Relations between Primal and Dual
           www3.nd.edu/~dgalvin1/30210/30210_F07/presentations/dual_opt.pdf
    Nshape)      z expecting Matrix or 3 or 4 listsr   r   c                     t        | d      S )Nr   )startr   )xs    r   r/   z_primal_dual.<locals>.<lambda>3  s    "1A. r   rt   yc                 N   g }fdt        | |      D        D ]  }|dk(  r
|dk(  rdgc S rt        |      }|j                  j                  r|j                  |j                  j
                  d   z  dk(  rt        |j                  j
                        dk(  sJ |j                         |j                  j
                  d   }|j                  t        |      |j                  j
                  d   z  |j                  t        |      z        }|j                  |       
 |S )Nc              3   6   K   | ]  \  }} ||        y wr+   r   )r9   r"   r#   ops      r   r:   z-_primal_dual.<locals>.ineq.<locals>.<genexpr>9  s     1tq!"Q(1s   TFr      r   )zipr   lhsis_Mulrhsargsrd   funcr   absrM   )Lr]   rx   rvfrX   factors     `   r   ineqz_primal_dual.<locals>.ineq7  s    1s1ay1 	ADyew O55<<AEEAEEJJqM$9Q$>quuzz?a/66/

1AtAwA6QHAIIaL	 	r   c                     | r| d   |z
  S | S Nr   r   )rt   rS   s     r   r/   z_primal_dual.<locals>.<lambda>G  s    !adQh ! r   )hasattrrd   rG   rm   ro   ri   r   rz   rL   rF   r   r   )r!   r   r"   rV   rU   r'   rl   r[   rS   rY   r#   rt   yTr   eqFr   s    `               r   _primal_dualr     s>   ^ bzD":%%1gq6?@@F77#aAE#DAqqJAq!Q	!A.Ac!C&%(34da45A	s1S65845tq!5	6	8	8B  
,B
1q5!A
261AtAE1b!"QR!VQ(;$<<<5 $ 55s   D.D3

D9
c                    i }g }g }t        ddt              }i }g }t        |      }| D ]!  }|dk(  r
|dk(  r y|j                  t        j
                  t        j                        rt        d      t        |t        t        f      r|j                  |j                  z
  }|j                  }	|	|z
  rt        d|	|z
  z        t        |	      dkD  r|j                  |       |	rJ|	j!                         }
|
|v rt        |d	d
      j#                         }|
|vr|||
<   ||
xx   |z  cc<   |s yt%        t'        d|z               |D ]  }
|j)                  |
d      }|s y|dk(  r|j                  |
       0|j*                  |j,                  }}|j.                  r%t1        |      }||z
  ||
<   |j                  |       y|j.                  r(|r%t1        |      }||z   ||
<   |j                  |       t1        |      }|j                  |       ||z   ||
<   |j                  |||z
  z
          |D ]&  }
t1        |      }||
z
  ||
<   |j                  |       ( |||fS )a  return `(np, d, aux)` where `np` is a list of nonpositive
    expressions that represent the given constraints (possibly
    rewritten in terms of auxilliary variables) expressible with
    nonnegative symbols, and `d` is a dictionary mapping a given
    symbols to an expression with an auxilliary variable. In some
    cases a symbol will be used as part of the change of variables,
    e.g. x: x - z1 instead of x: z1 - z2.

    If any constraint is False/empty, return None. All variables in
    ``constr`` are assumed to be unbounded unless explicitly indicated
    otherwise with a univariate constraint, e.g. ``x >= 0`` will
    restrict ``x`` to nonnegative values.

    The ``syms`` must be included so all symbols can be given an
    unbounded assumption if they are not otherwise bound with
    univariate conditions like ``x <= 3``.

    Examples
    ========

    >>> from sympy.solvers.simplex import _rel_as_nonpos
    >>> from sympy.abc import x, y
    >>> _rel_as_nonpos([x >= y, x >= 0, y >= 0], (x, y))
    ([-x + y], {}, [])
    >>> _rel_as_nonpos([x >= 3, x <= 5], [x])
    ([_z1 - 2], {x: _z1 + 3}, [_z1])
    >>> _rel_as_nonpos([x <= 5], [x])
    ([], {x: 5 - _z1}, [_z1])
    >>> _rel_as_nonpos([x >= 1], [x])
    ([], {x: _z1 + 1}, [_z1])
    zr   )rs   clsTFNz only finite bounds are permittedz&unexpected symbol(s) in constraint: %sr   )evaluatez
                only equalities like Eq(x, y) or non-strict
                inequalities like x >= y are allowed in lp, not %s)r   r	   sethasr   InfinityNegativeInfinityrG   
isinstancer   r   ltsgtsfree_symbolsrd   rM   popas_setrK   r   getinfsupis_infinitenext)constrsymsr]   npauxui
univariateunboundr"   freeirt   ivlrk   rl   us                  r   _rel_as_nonposr   M  sx   @ 	A	B
C	#QE	2BJGt9D  L9:55Q//0?@@a"b"ANNEt| <M  5zA~		!IIK<A.557J&$'JqMqMS(MJ (FHI(J K L L9LD  #NN1d#9NN1uuaee1==RAq5AaDJJqM]]H1u!

1 RAJJqMq5AaD IIa1q5k"9#>  H1u!

1
 q#:r   c                    t        |       }|D cg c]  }t        |       }}t        j                  g |g|z   D cg c]  }|j                   c}t                }t	        t        |            D ]]  }t        ||   t              s||   j                  ||   j                  z
  dk  ||<   |j                  ||   j                   dk         _ t        ||      }|t        t        d            |\  }}}|j                  |      }|D cg c]  }|j                  |       }}t        t!        |            |z   }	t#        ||	      \  }
}t#        |g|	      \  }}|
|||||	|fS c c}w c c}w c c}w )aD  return A, B, C, D, r, x+X, X for maximizing
    objective = Cx - D with constraints Ax <= B, introducing
    introducing auxilliary variables, X, as necessary to make
    replacements of symbols as given in r, {xi: expression with Xj},
    so all variables in x+X will take on nonnegative values.

    Every univariate condition creates a semi-infinite
    condition, e.g. a single ``x <= 3`` creates the
    interval ``[-oo, 3]`` while ``x <= 3`` and ``x >= 2``
    create an interval ``[2, 3]``. Variables not in a univariate
    expression will take on nonnegative values.
    r   z*
            Inconsistent/False constraint)r   r   unionr   rL   rd   r   r   r{   r}   rM   r   r   r   xreplacerh   r
   r   )	objectiveconstraintsr   r"   r   r   rY   r]   r   xxr'   r,   rO   rP   s                 r   _lp_matricesr     sp    		A)	*'!*	*B	*99@sRx8!q~~8@#%@D 3r7^ 'beR qEII1		)Q.BqEIIr!uyyjAo&' 	r4 Ay
 ,- !. / 	/JB3 	


1A!#	$A!**Q-	$B	$ 
gdm	s	"Br2&DAqsB'DAqaAq"c!!1 
+8" 
%s   E)E.
E3c                    t        ||      \  }}}}}}}	t        |       j                         }
d|
v rt        ||| |       \  }}}| }n"d|
v rt        ||||      \  }}}nt	        d      t        t        ||            }|rd|j                         D ci c]  \  }}||j                  |       }}}|j                  |       t        |      D ci c]  }||	vs|||    }}||fS c c}}w c c}w )aX  Return the optimization (min or max) of ``f`` with the given
    constraints. All variables are unbounded unless constrained.

    If `min_max` is 'max' then the results corresponding to the
    maximization of ``f`` will be returned, else the minimization.
    The constraints can be given as Le, Ge or Eq expressions.

    Examples
    ========

    >>> from sympy.solvers.simplex import _lp as lp
    >>> from sympy import Eq
    >>> from sympy.abc import x, y, z
    >>> f = x + y - 2*z
    >>> c = [7*x + 4*y - 7*z <= 3, 3*x - y + 10*z <= 6]
    >>> c += [i >= 0 for i in (x, y, z)]
    >>> lp(min, f, c)
    (-6/5, {x: 0, y: 0, z: 3/5})

    By passing max, the maximum value for f under the constraints
    is returned (if possible):

    >>> lp(max, f, c)
    (3/4, {x: 0, y: 3/4, z: 0})

    Constraints that are equalities will require that the solution
    also satisfy them:

    >>> lp(max, f, c + [Eq(y - 9*x, 1)])
    (5/7, {x: 0, y: 1, z: 1/7})

    All symbols are reported, even if they are not in the objective
    function:

    >>> lp(min, x, [y + x >= 3, x >= 0])
    (0, {x: 0, y: 3})
    maxr1   zexpecting min or max)r   strlowerrE   rG   dictrz   itemsr   updater
   )min_maxr   r   r'   r,   rO   rP   r]   r   r   howrR   rT   rS   orX   r`   s                    r   _lpr     s	   P *!V4Aq!Q2s
g,


C| Aq1"qb)AqC	#1aA&1a/00 	SQZA*+'')4$!QQ

144	%aj9ASLQ!W99 a4K 5 :s   C+	C1C1c                 $    t        t        | |      S )a  return minimum of linear equation ``f`` under
    linear constraints expressed using Ge, Le or Eq.

    All variables are unbounded unless constrained.

    Examples
    ========

    >>> from sympy.solvers.simplex import lpmin
    >>> from sympy import Eq
    >>> from sympy.abc import x, y
    >>> lpmin(x, [2*x - 3*y >= -1, Eq(x + 3*y, 2), x <= 2*y])
    (1/3, {x: 1/3, y: 5/9})

    Negative values for variables are permitted unless explicitly
    exluding, so minimizing ``x`` for ``x <= 3`` is an
    unbounded problem while the following has a bounded solution:

    >>> lpmin(x, [x >= 0, x <= 3])
    (0, {x: 0})

    Without indicating that ``x`` is nonnegative, there
    is no minimum for this objective:

    >>> lpmin(x, [x <= 3])
    Traceback (most recent call last):
    ...
    sympy.solvers.simplex.UnboundedLPError:
    Objective function can assume arbitrarily large values!

    See Also
    ========
    linprog, lpmax
    )r   r1   r   r   s     r   lpminr   /  s    F sAvr   c                 $    t        t        | |      S )a"  return maximum of linear equation ``f`` under
    linear constraints expressed using Ge, Le or Eq.

    All variables are unbounded unless constrained.

    Examples
    ========

    >>> from sympy.solvers.simplex import lpmax
    >>> from sympy import Eq
    >>> from sympy.abc import x, y
    >>> lpmax(x, [2*x - 3*y >= -1, Eq(x+ 3*y,2), x <= 2*y])
    (4/5, {x: 4/5, y: 2/5})

    Negative values for variables are permitted unless explicitly
    exluding:

    >>> lpmax(x, [x <= -1])
    (-1, {x: -1})

    If a non-negative constraint is added for x, there is no
    possible solution:

    >>> lpmax(x, [x <= -1, x >= 0])
    Traceback (most recent call last):
    ...
    sympy.solvers.simplex.InfeasibleLPError: inconsistent/False constraint

    See Also
    ========
    linprog, lpmin
    )r   r   r   s     r   lpmaxr   U  s    B sAvr   c                 "   g }dgt        |       z  fd}dfd	}g }t        |       D ]  \  }\  }}|||j                  |        |b |       }d||<   d| |       <   |g}	|j                  ||	f       dgt        |      z  }d||<   d| |       <   | g}	|j                  ||	f       |e|rb |       }d||<   d| |       <   |g}	|j                  ||	f       dgt        |      z  }d||<   d| |       <   | g}	|j                  ||	f        |       }d||<   d| |       <   |g}	|j                  ||	f       dgt        |      z  }d||<   d| |       <   | g}	|j                  ||	f       dgt        |      z  }d||<   d| |       <   ||z
  g}	|j                  ||	f        |D ]z  } |d      }dg}	d||<   d| |       <   d| |       dz
  <   |j                  ||	f       dgt        |      z  }d||<   d| |       <   d| |       dz
  <   |j                  ||	f       | t        |D 
cg c]#  \  }
}|
dgt              t        |
      z
  z  z   % c}}
      t        |D cg c]  }|d   	 c}      fS c c}}
w c c}w )Nr   c                       t               dz
  S )Nr   )rd   )Rs   r   rU   z_handle_bounds.<locals>.n  s    1vzr   r   c                 8    j                  dg| z         d d  S r   )extend)incr   s    r   Arowz_handle_bounds.<locals>.Arow  s    	!str   r;   ry   )r   )rd   rN   rM   r   )boundsr   rU   r   rowrt   rk   rl   r'   r,   r]   rY   r"   r   s                @r   _handle_boundsr   y  s    G	
c&kA Cv& 0	6Aq9NN1YAAaDAacFAJJ1vc!fAAaDAacFAJJ1vYF!!#C

Aq6"C#a&L!!#RD

Aq6"  AAaDAacFAJJ1vc!fAAaDAacFAJJ1vc!fAAaDAacFQAJJ1va0f  GC!!#!#'


Aq6C#a&L!!#!#'


Aq6 c:sq1aS#a&3q6/**: 
%A1Q4%&' ':%s   :(J
2J
c                    t        |       }|j                  dk7  r|j                  dk(  r|j                  }|j                  dk7  rt	        d      |s:|rt	        d      t        d|j                        t        |j                  d      }}n||fD cg c]  }t        |       c}\  }}|j                  |j                  k7  rt	        d      ||ot	        d      ||fD cg c]  }t        |       c}\  }}|j                  |      }|j                  |       }|j                  |      }|j                  |       }|U|i k(  sO|dk(  sIt        |      t        u rt        |      d	k(  r|g|j                  z  }nt        |      |j                  k(  rt        d
 |D              rnot        |      t        u rPt        d |j                         D              r0|}dg|j                  z  }|r*|j                         \  }}	|	||<   |rnt	        d|z        t        |      \  }
}|
j                  |j                  z
  }|r6t        |t        |j                  |      g|
gg      }|j                  |      }n|
}|}|j                  t        d|            }n|j                   }t!        |||      \  }}}||d|  fS c c}w c c}w )a  Return the minimization of ``c*x`` with the given
    constraints ``A*x <= b`` and ``A_eq*x = b_eq``. Unless bounds
    are given, variables will have nonnegative values in the solution.

    If ``A`` is not given, then the dimension of the system will
    be determined by the length of ``C``.

    By default, all variables will be nonnegative. If ``bounds``
    is given as a single tuple, ``(lo, hi)``, then all variables
    will be constrained to be between ``lo`` and ``hi``. Use
    None for a ``lo`` or ``hi`` if it is unconstrained in the
    negative or positive direction, respectively, e.g.
    ``(None, 0)`` indicates nonpositive values. To set
    individual ranges, pass a list with length equal to the
    number of columns in ``A``, each element being a tuple; if
    only a few variables take on non-default values they can be
    passed as a dictionary with keys giving the corresponding
    column to which the variable is assigned, e.g. ``bounds={2:
    (1, 4)}`` would limit the 3rd variable to have a value in
    range ``[1, 4]``.

    Examples
    ========

    >>> from sympy.solvers.simplex import linprog
    >>> from sympy import symbols, Eq, linear_eq_to_matrix as M, Matrix
    >>> x = x1, x2, x3, x4 = symbols('x1:5')
    >>> X = Matrix(x)
    >>> c, d = M(5*x2 + x3 + 4*x4 - x1, x)
    >>> a, b = M([5*x2 + 2*x3 + 5*x4 - (x1 + 5)], x)
    >>> aeq, beq = M([Eq(3*x2 + x4, 2), Eq(-x1 + x3 + 2*x4, 1)], x)
    >>> constr = [i <= j for i,j in zip(a*X, b)]
    >>> constr += [Eq(i, j) for i,j in zip(aeq*X, beq)]
    >>> linprog(c, a, b, aeq, beq)
    (9/2, [0, 1/2, 0, 1/2])
    >>> assert all(i.subs(dict(zip(x, _[1]))) for i in constr)

    See Also
    ========
    lpmin, lpmax
    r   C must be a single row.A and b must both be givenr   'number of columns in A and C must matchN A_eq and b_eq must both be givenr=   ry   c              3   ^   K   | ]%  }t        |      t        u xr t        |      d k(   ' ywry   Ntyperg   rd   r8   s     r   r:   zlinprog.<locals>.<genexpr>  0      +B56Q5 0SVq[0+B   +-c              3   ^   K   | ]%  }t        |      t        u xr t        |      d k(   ' ywr   r   r8   s     r   r:   zlinprog.<locals>.<genexpr>  1      ** Q5 0SVq[0**r   unexpected bounds %s)r   rI   rH   rF   rG   r   col_joinr   rg   rd   rJ   r   valuespopitemr   row_joinrE   )r[   r'   rl   A_eqb_eqr   rO   r"   dbr#   A_b_r   r   rT   rS   s                   r   linprogr     s   X 	q	Avv{qvv{CCvv{233 9:: Qqvvq!11$%q6*aq	*1vvBCC ||?@@*.6AfQi6
dJJtJJuJJtJJuNflf	.A<5 S[A%5X&F[AFF"s +B:@+B (B&\T!c **** '* B[166)Fzz|1q	  3f<=='BggE!&&#./"67A

2AAAJJuQ}%vvgq!QGAq!a#h;a + 7s   J?#Kc           
         ddl m} t        |       }|j                  dk7  r|j                  dk(  r|j
                  }|j                  dk7  rt        d      |s:|rt        d      t        d|j                        t        |j                  d      }}n||fD cg c]  }t        |       c}\  }}|j                  |j                  k7  rt        d      ||)t        d      ||fD cg c]  }t        |       c}\  }}||i k(  s|dk(  st        |      t        u rt        |      d	k(  r|g|j                  z  }nt        |      |j                  k(  rt        d
 |D              rnot        |      t        u rPt        d |j                         D              r0|}	dg|j                  z  }|	r*|	j                         \  }}
|
||<   |	rnt        d|z        t         |d|j                  dz   z              }||z  d   t        ||z  |      D 
cg c]
  \  }}
||
k   c}
}t        ||z  |      D 
cg c]  \  }}
t!        ||
       c}
}z   } }t#        |      D ]o  \  }\  }}|||| j%                  ||   |k         (|| j%                  ||   |k\         B| j%                  ||   |k\         | j%                  ||   |k         q || fS c c}w c c}w c c}
}w c c}
}w )Nr   )symbolsr   r   r   r   r   r=   ry   c              3   ^   K   | ]%  }t        |      t        u xr t        |      d k(   ' ywr   r   r8   s     r   r:   zshow_linprog.<locals>.<genexpr>Z  r   r   c              3   ^   K   | ]%  }t        |      t        u xr t        |      d k(   ' ywr   r   r8   s     r   r:   zshow_linprog.<locals>.<genexpr>]  r   r   r   zx1:%s)sympyr   r   rI   rH   rF   rG   r   r   rg   rd   rJ   r   r   r   rz   r   rN   rM   )r[   r'   rl   r   r   r   r   rO   r"   r   r#   rt   r   lohis                  r   show_linprogr   9  s   q	Avv{qvv{CCvv{233 9:: Qqvvq!11$%q6*aq	*1vvBCC ||?@@*.6AfQi6
dNflf	.A<5 S[A%5X&F[AFF"s +B:@+B (B&\T!c **** '* B[166)Fzz|1q	  3f<==ww!&&(+,-AQ3(S1a[1caQT1DQRFSWHX4Y1R!W4YYaA ( 	8B:"*:HHQqT2XZHHQqT2XHHQqT2XHHQqT2X	 Q3JW + 7, 24Ys   K)KK5K#
)NF)Fr+   )T)NNNNN)+r   
sympy.corer   sympy.core.exprtoolsr   sympy.core.relationalr   r   r   sympy.core.singletonr   sympy.core.symbolr	   sympy.core.sortingr
   $sympy.functions.elementary.complexesr   sympy.matrices.denser   r   sympy.solvers.solvesetr   sympy.utilities.iterablesr   sympy.utilities.miscr   	Exceptionr   r   r(   r3   rE   ri   rm   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s   =~  - , , " # & 5 . 6 6 +	y 	&		 	*BMs+r+)\$0o=dod("VBJ#L!HQ'hjX<r   