
    sgI|                        d 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
 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mZ ddlmZ  G d de      Ze
j<                  e
j>                  e
j@                  e
jB                  e
jD                  hZ#dZ$ G d d      Z%d Z&d Z'd Z(d Z) G d d      Z* G d d      Z+ G d d      Z,y)a  Implements "A Fast Linear-Arithmetic Solver for DPLL(T)"

The LRASolver class defined in this file can be used
in conjunction with a SAT solver to check the
satisfiability of formulas involving inequalities.

Here's an example of how that would work:

    Suppose you want to check the satisfiability of
    the following formula:

    >>> from sympy.core.relational import Eq
    >>> from sympy.abc import x, y
    >>> f = ((x > 0) | (x < 0)) & (Eq(x, 0) | Eq(y, 1)) & (~Eq(y, 1) | Eq(1, 2))

    First a preprocessing step should be done on f. During preprocessing,
    f should be checked for any predicates such as `Q.prime` that can't be
    handled. Also unequality like `~Eq(y, 1)` should be split.

    I should mention that the paper says to split both equalities and
    unequality, but this implementation only requires that unequality
    be split.

    >>> f = ((x > 0) | (x < 0)) & (Eq(x, 0) | Eq(y, 1)) & ((y < 1) | (y > 1) | Eq(1, 2))

    Then an LRASolver instance needs to be initialized with this formula.

    >>> from sympy.assumptions.cnf import CNF, EncodedCNF
    >>> from sympy.assumptions.ask import Q
    >>> from sympy.logic.algorithms.lra_theory import LRASolver
    >>> cnf = CNF.from_prop(f)
    >>> enc = EncodedCNF()
    >>> enc.add_from_cnf(cnf)
    >>> lra, conflicts = LRASolver.from_encoded_cnf(enc)

    Any immediate one-lital conflicts clauses will be detected here.
    In this example, `~Eq(1, 2)` is one such conflict clause. We'll
    want to add it to `f` so that the SAT solver is forced to
    assign Eq(1, 2) to False.

    >>> f = f & ~Eq(1, 2)

    Now that the one-literal conflict clauses have been added
    and an lra object has been initialized, we can pass `f`
    to a SAT solver. The SAT solver will give us a satisfying
    assignment such as:

    (1 = 2): False
    (y = 1): True
    (y < 1): True
    (y > 1): True
    (x = 0): True
    (x < 0): True
    (x > 0): True

    Next you would pass this assignment to the LRASolver
    which will be able to determine that this particular
    assignment is satisfiable or not.

    Note that since EncodedCNF is inherently non-deterministic,
    the int each predicate is encoded as is not consistent. As a
    result, the code bellow likely does not reflect the assignment
    given above.

    >>> lra.assert_lit(-1) #doctest: +SKIP
    >>> lra.assert_lit(2) #doctest: +SKIP
    >>> lra.assert_lit(3) #doctest: +SKIP
    >>> lra.assert_lit(4) #doctest: +SKIP
    >>> lra.assert_lit(5) #doctest: +SKIP
    >>> lra.assert_lit(6) #doctest: +SKIP
    >>> lra.assert_lit(7) #doctest: +SKIP
    >>> is_sat, conflict_or_assignment = lra.check()

    As the particular assignment suggested is not satisfiable,
    the LRASolver will return unsat and a conflict clause when
    given that assignment. The conflict clause will always be
    minimal, but there can be multiple minimal conflict clauses.
    One possible conflict clause could be `~(x < 0) | ~(x > 0)`.

    We would then add whatever conflict clause is given to
    `f` to prevent the SAT solver from coming up with an
    assignment with the same conflicting literals. In this case,
    the conflict clause `~(x < 0) | ~(x > 0)` would prevent
    any assignment where both (x < 0) and (x > 0) were both
    true.

    The SAT solver would then find another assignment
    and we would check that assignment with the LRASolver
    and so on. Eventually either a satisfying assignment
    that the SAT solver and LRASolver agreed on would be found
    or enough conflict clauses would be added so that the
    boolean formula was unsatisfiable.


This implementation is based on [1]_, which includes a
detailed explanation of the algorithm and pseudocode
for the most important functions.

[1]_ also explains how backtracking and theory propagation
could be implemented to speed up the current implementation,
but these are not currently implemented.

TODO:
 - Handle non-rational real numbers
 - Handle positive and negative infinity
 - Implement backtracking and theory proposition
 - Simplify matrix by removing unused variables using Gaussian elimination

References
==========

.. [1] Dutertre, B., de Moura, L.:
       A Fast Linear-Arithmetic Solver for DPLL(T)
       https://link.springer.com/chapter/10.1007/11817963_11
    )linear_eq_to_matrix)eye)	Predicate)AppliedPredicate)Q)Dummy)Mul)Add)EqNe)sympify)S)RationalooMatrixc                       e Zd ZdZy)UnhandledInputzf
    Raised while creating an LRASolver if non-linearity
    or non-rational numbers are present.
    N)__name__
__module____qualname____doc__     T/var/www/html/venv/lib/python3.12/site-packages/sympy/logic/algorithms/lra_theory.pyr   r      s    r   r   Tc                   f    e Zd ZdZd Zedd       Zd Zd ZddZ	ddZ
d Zd	 Zd
 Zed        Zy)	LRASolvera^  
    Linear Arithmetic Solver for DPLL(T) implemented with an algorithm based on
    the Dual Simplex method. Uses Bland's pivoting rule to avoid cycling.

    References
    ==========

    .. [1] Dutertre, B., de Moura, L.:
           A Fast Linear-Arithmetic Solver for DPLL(T)
           https://link.springer.com/chapter/10.1007/11817963_11
    c                 \   || _         || _        t        d |D              rt        d      t        d |j	                         D              rt        d      t        |      t        |      t        |      z   }}|dk7  r|j                  ||fk(  sJ | j                   r|dd||z
  df   t        |       k(  sJ || _        |j                         D 	
ci c]  \  }	}
|
|	
 c}
}	| _
        || _        || _        || _        ||z   | _        t        |      | _        d| _        d| _        yc c}
}	w )zN
        Use the "from_encoded_cnf" method to create a new LRASolver.
        c              3   >   K   | ]  }t        |t                 y wN)
isinstancer   ).0as     r   	<genexpr>z%LRASolver.__init__.<locals>.<genexpr>   s     6q:a**6s   z$Non-rational numbers are not handledc              3   R   K   | ]  }t        |j                  t                ! y wr    )r!   boundr   )r"   bs     r   r$   z%LRASolver.__init__.<locals>.<genexpr>   s     SQ:aggx00Ss   %'r   NT)
run_checkss_subsanyr   valueslenshaper   enc_to_boundaryitemsboundary_to_encAslacknonslackall_varset	slack_setis_satresult)selfr1   slack_variablesnonslack_variablesr.   r)   testing_modemnkeyvalues              r   __init__zLRASolver.__init__   s     '6A66 !GHHS/:P:P:RSS !GHH?#S%9#>P:Q%Q1677q!f$$$??Q!W:#a&(((.=L=R=R=TUzsEs
U$
*)O;_-  Vs   D(c                 p
   i }g }g }d}i }g }|r't        | j                  j                         d       }n| j                  j                         }t               }	i }
g }|D ]  \  }}t	        |t
              r ||	      }t	        |t              s?|dk(  r|j                  |g       G|dk(  r|j                  | g       `t        d|       |j                  t        v sJ |j                  t        j                  k(  s|j                  t        j                  k(  rt        | d      |j                  j                  s|j                  j                  rt!        | d      |j                  t"        k(  s|j                  t"        k(  rt!        | d	      t%        |      }|dk(  r|j                  |g       \|dk(  r|j                  | g       v|t!        | d      |j                  |j                  z
  }|j                  t&        j(                  t&        j*                  fv r| }|j                  t&        j,                  t&        j(                  fv r|dk  }n]|j                  t&        j.                  t&        j*                  fv r|dk  }n+|j                  t&        j0                  k(  sJ t3        |d      }|dk(  r|j                  |g       v|dk(  r|j                  | g       t5        |      \  }}t7        |      \  }}||z  }t9        |      }|D ]N  }t7        |      \  }}t;        |j<                        dkD  sJ ||
vs0t?        |      |
|<   |j                  |       P t;        |      dkD  rU||vrK|dz  }t        d|       }t?        |      |
|<   |j                  |       |||<   |j                  ||z
         ||   }n|d   }|dk7  sJ |j                  t&        j0                  k(  }|s|dkD  nd
}|j                  t&        j*                  t&        j.                  fv }tA        |
|   | |||      }|||<    ||z   D cg c]  }|j<                   }}tC        d |D              sJ tE        d |D              }t;        |      dkD  r)t;        tG        jH                  |       |k  rt!        d      tK        |||z         \  }}|D cg c]  }|
|   	 }}|D cg c]  }|
|   	 }}tM        ||z         D ]  \  } }| |_'         tQ        ||||||      |fS c c}w c c}w c c}w )a  
        Creates an LRASolver from an EncodedCNF object
        and a list of conflict clauses for propositions
        that can be simplified to True or False.

        Parameters
        ==========

        encoded_cnf : EncodedCNF

        testing_mode : bool
            Setting testing_mode to True enables some slow assert statements
            and sorting to reduce nonterministic behavior.

        Returns
        =======

        (lra, conflicts)

        lra : LRASolver

        conflicts : list
            Contains a one-literal conflict clause for each proposition
            that can be simplified to True or False.

        Example
        =======

        >>> from sympy.core.relational import Eq
        >>> from sympy.assumptions.cnf import CNF, EncodedCNF
        >>> from sympy.assumptions.ask import Q
        >>> from sympy.logic.algorithms.lra_theory import LRASolver
        >>> from sympy.abc import x, y, z
        >>> phi = (x >= 0) & ((x + y <= 2) | (x + 2 * y - z >= 6))
        >>> phi = phi & (Eq(x + y, 2) | (x + 2 * y - z > 4))
        >>> phi = phi & Q.gt(2, 1)
        >>> cnf = CNF.from_prop(phi)
        >>> enc = EncodedCNF()
        >>> enc.from_cnf(cnf)
        >>> lra, conflicts = LRASolver.from_encoded_cnf(enc, testing_mode=True)
        >>> lra #doctest: +SKIP
        <sympy.logic.algorithms.lra_theory.LRASolver object at 0x7fdcb0e15b70>
        >>> conflicts #doctest: +SKIP
        [[4]]
        r   c                     t        |       S r    )str)xs    r   <lambda>z,LRASolver.from_encoded_cnf.<locals>.<lambda>   s    SVWXSY r   r?   TFzUnhandled Predicate: z contains nanz  contains an imaginary componentz contains infinityNz could not be simplified   sc              3   8   K   | ]  }t        |      d kD    yw)r   Nr,   r"   symss     r   r$   z-LRASolver.from_encoded_cnf.<locals>.<genexpr>Y  s     0T3t9q=0   c              3   2   K   | ]  }t        |        y wr    rK   rL   s     r   r$   z-LRASolver.from_encoded_cnf.<locals>.<genexpr>Z  s     0Ts4y0s   zNonlinearity is not handled))sortedencodingr/   r   r!   r   r   append
ValueErrorfunctionALLOWED_PREDlhsr   NaNrhsis_imaginaryr   r   _eval_binrelr   gegtlelteqr   _sep_const_terms_sep_const_coeff_list_termsr,   free_symbolsLRAVariableBoundaryallsumr5   unionr   	enumeratecol_idxr   )!encoded_cnfr<   rQ   r1   basics_countr)   nonbasicencoded_cnf_items	empty_varvar_to_lra_var	conflictspropencexprboolvarsconst	var_coefftermsterm_dvarequalityupperstrictr'   vfsfs_countnbidxs!                                    r   from_encoded_cnfzLRASolver.from_encoded_cnf   s   r  &{';';'A'A'CIY Z + 4 4 : : <G		* S	ID#$	*Id$454<$$cU+5=$$sdV, #8!?@@==L000xx155 DHH$5 D6!788xx$$(=(=$v-M%NOOxx2~R$v-?%@AA%Dt|  #'  3$($v-E%FGG88dhh&D}}qtt,u }}qtt,	144,.q}},,,${t|  #'  3$( +40KD%.t4OD)I%E%E **40a4,,-111~-+6t+<N4(OOD)* 5zA~v%qLG'm,A(3AN1%LLO#$F4LHHTAX&TlAh>!>}},H)1IMtE]]qttQTTl2F,ufeXvNAHSMgS	j '/&67ann770R00000R00r7Q;C		2/(: !>??"1h&67119:2N2&::,12q"22!(U"23 	HCCK	 E8Xv|LiWW 8 ;2s   T)T.,T3c                     d| _         | j                  D ]d  }t        t        d       d      |_        d|_        d|_        t        t        d      d      |_        d|_        d|_        t        dd      |_	        f y)z\
        Resets the state of the LRASolver to before
        anything was asserted.
        Ninfr   F)
r8   r4   LRARationalfloatlowerlower_from_eqlower_from_negr   upper_from_eqassignr9   r~   s     r   reset_boundszLRASolver.reset_boundsf  sr    
 << 	+C#U5\M15CI %C!&C#E%L!4CI$C!&C$Q*CJ	+r   c                    t        |      | j                  vryt        s|dk  ry| j                  t        |         }|j                  |j                  |dk  }}}|j
                  r|ry|j                  |k7  }|j                  |k7  r|rdnd}t        ||      }nt        |d      }|j
                  r:| j                  ||d|      }|r|d   dk(  r|}	nC| j                  ||d|      }
|
}	n+|r| j                  |||      }	n| j                  |||      }	| j                  r|| j                  vr|	du | _        |	S d| _        |	S )	a  
        Assert a literal representing a constraint
        and update the internal state accordingly.

        Note that due to peculiarities of this implementation
        asserting ~(x > 0) will assert (x <= 0) but asserting
        ~Eq(x, 0) will not do anything.

        Parameters
        ==========

        enc_constraint : int
            A mapping of encodings to constraints
            can be found in `self.enc_to_boundary`.

        Returns
        =======

        None or (False, explanation)

        explanation : set of ints
            A conflict clause that "explains" why
            the literals asserted so far are unsatisfiable.
        Nr   rH   T)from_equalityfrom_negF)r   )absr.   HANDLE_NEGATIONr~   r&   r   r   r   r   _assert_lower_assert_upperr7   r6   )r9   enc_constraintboundarysymcnegatedr   deltares1resres2s              r   
assert_litzLRASolver.assert_litu  sU   2 ~d&:&::>A#5''N(;<",,8JQ')??g%BQEAu%AAq!A%%c1D7%SDQ5())#qw)W$$S!g$>C$$S!g$>C;;3dnn4+DK 
  DK
r   c                 d   | j                   r| j                   d   dk7  sJ d| _         ||j                  k\  ry||j                  k  r|j                  d   dk\  du sJ |d   dk  du sJ t        j	                  |      \  }}t        ||d   |d   dk7  d|      }|r|j                         }|rdnd}| | j                  |   z  | | j                  |   z  g}	d|	f| _         | j                   S ||_        ||_        ||_        || j                  v r!|j                  |kD  r| j                  ||       | j                  rot        d | j                  D              rS| j                  }
t!        | j                  D cg c]  }|j                  d    c}      }t        d	 |
|z  D              sJ yc c}w )
a;  
        Adjusts the upper bound on variable xi if the new upper bound is
        more limiting. The assignment of variable xi is adjusted to be
        within the new bound if needed.

        Also calls `self._update` to update the assignment for slack variables
        to keep all equalities satisfied.
        r   FNrH   Tr~   rx   r   r   r   r   c              3      K   | ]=  }|j                   d    t        d      k7  xr |j                   d    t        d       k7   ? ywr   r   Nr   r   r"   r   s     r   r$   z*LRASolver._assert_upper.<locals>.<genexpr>  H      #:'( $%88A;%,#>#_188A;SXY^S_R_C_#_ #:   AAc              3   8   K   | ]  }t        |      d k    ywg|=Nr   r"   vals     r   r$   z*LRASolver._assert_upper.<locals>.<genexpr>       ?#s3x+-?rN   )r8   r   r   re   
from_lowerget_negatedr0   r   upper_from_negr3   r   _updater(   rf   r4   r1   r   r9   xicir   r   lit1neg1lit2neg2conflictMr   Xs                r   r   zLRASolver._assert_upper  s    ;;;;q>U***>=HHQK1$---qEQJ4'''!,,R0JD$"Q%1
$YfgD'')!2qDd224884%@T@TUY@Z:Z[H/DK;;($299r>LLR ??s #:,0LL#:  :AT\\::;A?Q???? ;   8F-c                 d   | j                   r| j                   d   dk7  sJ d| _         ||j                  k  ry||j                  kD  r|j                  d   dk  du sJ |d   dk\  du sJ t        j	                  |      \  }}t        ||d   |d   dk7  d|      }|r|j                         }|rdnd}| | j                  |   z  | | j                  |   z  g}	d|	f| _         | j                   S ||_        ||_        ||_        || j                  v r!|j                  |k  r| j                  ||       | j                  rot        d | j                  D              rS| j                  }
t!        | j                  D cg c]  }|j                  d    c}      }t        d	 |
|z  D              sJ yc c}w )
a;  
        Adjusts the lower bound on variable xi if the new lower bound is
        more limiting. The assignment of variable xi is adjusted to be
        within the new bound if needed.

        Also calls `self._update` to update the assignment for slack variables
        to keep all equalities satisfied.
        r   FNrH   Tr   r   c              3      K   | ]=  }|j                   d    t        d      k7  xr |j                   d    t        d       k7   ? ywr   r   r   s     r   r$   z*LRASolver._assert_lower.<locals>.<genexpr>   r   r   c              3   8   K   | ]  }t        |      d k    ywr   r   r   s     r   r$   z*LRASolver._assert_lower.<locals>.<genexpr>  r   rN   )r8   r   r   re   
from_upperr   r0   r   r   r3   r   r   r(   rf   r4   r1   r   r   s                r   r   zLRASolver._assert_lower  s    ;;;;q>U***>=HHQK1$---qEQJ4'''!,,R0JD$"Q%1
%ZghD'')!2qDd22488$t?S?STX?Y9YZH/DK;;($299r>LLR ??s #:,0LL#:  :AT\\::;A?Q???? ;r   c                     |j                   }t        | j                        D ]:  \  }}| j                  ||f   }|j                  ||j                  z
  |z  z   |_        < ||_        y)z
        Updates all slack variables that have equations that contain
        variable xi so that they stay satisfied given xi is equal to v.
        N)rj   ri   r2   r1   r   )r9   r   r   ijr'   ajis          r   r   zLRASolver._update  s`    
 JJdjj) 	6DAq&&A,Cxx1ryy=#"55AH	6 	r   c                 0   | j                   r'd| j                  D ci c]  }||j                   c}fS | j                  r| j                  S ddlm} | j                  j                         }t        | j                        D ci c]  \  }}||
 }}}t        | j                        }d}	 |dz  }| j                  rt        d |D              sJ t        d | j                  D              rD || j                  D 	cg c]  }	|	j                  d    c}	      }
t        d ||
z  D              sJ t        d | j                  D              sJ t        d	 | j                  D              sJ |D cg c]7  }|j                  |j                  k  s|j                  |j                  kD  s6|9 }}t!        |      dk(  r'd| j                  D ci c]  }||j                   c}fS t#        |d
       }||   }|j                  |j                  k  r|D cg c]^  }|||j$                  f   dkD  r|j                  |j                  k  s-|||j$                  f   dk  r|j                  |j                  kD  r|` }}t!        |      dk(  r|D cg c]  }|||j$                  f   dkD  s| }}|D cg c]  }|||j$                  f   dk  s| }}g }||D cg c]  }t&        j)                  |       c}z  }||D cg c]  }t&        j+                  |       c}z  }|j-                  t&        j+                  |             |D cg c]  \  }}| | j.                  |   z   }}}d|fS t#        |t0              }| j3                  ||||||j                        }|j                  |j                  kD  r|D cg c]^  }|||j$                  f   dk  r|j                  |j                  k  s-|||j$                  f   dkD  r|j                  |j                  kD  r|` }}t!        |      dk(  r|D cg c]  }|||j$                  f   dkD  s| }}|D cg c]  }|||j$                  f   dk  s| }}g }||D cg c]  }t&        j)                  |       c}z  }||D cg c]  }t&        j+                  |       c}z  }|j-                  t&        j)                  |             |D cg c]  \  }}| | j.                  |   z   }}}d|fS t#        |d       }| j3                  ||||||j                        }c c}w c c}}w c c}	w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}}w c c}w c c}w c c}w c c}w c c}w c c}}w )a  
        Searches for an assignment that satisfies all constraints
        or determines that no such assignment exists and gives
        a minimal conflict clause that "explains" why the
        constraints are unsatisfiable.

        Returns
        =======

        (True, assignment) or (False, explanation)

        assignment : dict of LRAVariables to values
            Assigned values are tuples that represent a rational number
            plus some infinatesimal delta.

        explanation : set of ints
        Tr   r   rH   c              3      K   | ]>  }|j                   |j                  k\  d k(  xr |j                   |j                  k  d k(   @ yw)TN)r   r   r   )r"   r   s     r   r$   z"LRASolver.check.<locals>.<genexpr>4  sA     vgiRYY"((2t;b299PRPXPXCX]aBabvs   AAc              3      K   | ]=  }|j                   d    t        d      k7  xr |j                   d    t        d       k7   ? ywr   r   r   s     r   r$   z"LRASolver.check.<locals>.<genexpr>8  sD      :'( xx{eEl2Sqxx{uU|m7SS :r   c              3   8   K   | ]  }t        |      d k    ywr   r   r   s     r   r$   z"LRASolver.check.<locals>.<genexpr>;  s     Cs3x)3CrN   c              3   @   K   | ]  }|j                   d    dk    ywrH   r   N)r   r"   rE   s     r   r$   z"LRASolver.check.<locals>.<genexpr>C       Aq1771:?A   c              3   @   K   | ]  }|j                   d    dk\    ywr   )r   r   s     r   r$   z"LRASolver.check.<locals>.<genexpr>D  r   r   c                     | j                   S r    rj   r   s    r   rF   z!LRASolver.check.<locals>.<lambda>K  s
     r   rG   Fc                     | j                   S r    r   r   s    r   rF   z!LRASolver.check.<locals>.<lambda>o  s
    QYY r   )r7   r4   r   r8   sympy.matrices.denser   r1   copyri   r2   r5   r3   r(   rf   r   r   r,   minrj   re   r   r   rR   r0   rD   _pivot_and_update)r9   r~   r   r   r   rI   rl   rn   	iterationr   r   r'   candr   r   N_plusN_minusr   r   negxjs                        r   checkzLRASolver.check  s   $ ;;T\\Bc#szz/BBB;;;;/FFKKM"+DJJ"78$!QA88t}}%	NIvmuvvvv  :,0LL: :T\\BBCACqsCCCC ADLLAAAAADLLAAAA$Q!177(:ahh>PAQDQ4yA~F#c3::oFFFT23Bb	Ayy288#%- Lram,q0RYY5Iam,q0RYY5I  L L t9>+3LRqBJJ7G!7KbLFL,4Mb!RZZ-8H18LrMGM!H6 JR!4!4R!8 JJH7 KR!4!4R!8 KKHOOH$7$7$;<KSTCT%9%9!%< <THT (?*3'**1eXr2rxxPyy288#%- Lram,q0RYY5Iam,q0RYY5I  L L t9>+3LRqBJJ7G!7KbLFL,4Mb!RZZ-8H18LrMGM!H7 KR!4!4R!8 KKH6 JR!4!4R!8 JJHOOH$7$7$;<KSTCT%9%9!%< <THT (?*#67**1eXr2rxxPC  C 9  C R GL MM !K KTL
 MM !L J  Us   U U=U17U)UUA#UU&U0U$
U$U)=U.U3:A#U91U>U>V/V<V"V,Vc                    ||   |j                   }}|||f   dk7  sJ ||j                  z
  d|||f   z  z  }	||_        |j                  |	z   |_        |D ]+  }
|
|k7  s	||
   }|||f   }|
j                  |	|z  z   |
_        - ||   ||<   ||= |j                  |       |j                  |       | j	                  |||      S )z
        Pivots basic variable xi with nonbasic variable xj,
        and sets value of xi to v and adjusts the values of all basic variables
        to keep equations satisfied.
        r   rH   )rj   r   addremove_pivot)r9   r   rl   rn   r   r   r   r   r   thetaxkkakjs                r   r   zLRASolver._pivot_and_updater  s     Ry"**1Aw!||RYY1QT7+	II%	 	2BRx"I1gIIc	1			2 "Ib	"IR{{1a##r   c                 ,   | |ddf   | dd|f   | ||f   c}}}|dk(  rt        d      | j                         }||ddf    |z  ||ddf<   t        | j                  d         D ]*  }||k7  s	||ddf   |||f   ||ddf   z  z   ||ddf<   , |S )a  
        Performs a pivot operation about entry i, j of M by performing
        a series of row operations on a copy of M and returing the result.
        The original M is left unmodified.

        Conceptually, M represents a system of equations and pivoting
        can be thought of as rearranging equation i to be in terms of
        variable j and then substituting in the rest of the equations
        to get rid of other occurances of variable j.

        Example
        =======

        >>> from sympy.matrices.dense import Matrix
        >>> from sympy.logic.algorithms.lra_theory import LRASolver
        >>> from sympy import var
        >>> Matrix(3, 3, var('a:i'))
        Matrix([
        [a, b, c],
        [d, e, f],
        [g, h, i]])

        This matrix is equivalent to:
        0 = a*x + b*y + c*z
        0 = d*x + e*y + f*z
        0 = g*x + h*y + i*z

        >>> LRASolver._pivot(_, 1, 0)
        Matrix([
        [ 0, -a*e/d + b, -a*f/d + c],
        [-1,       -e/d,       -f/d],
        [ 0,  h - e*g/d,  i - f*g/d]])

        We rearrange equation 1 in terms of variable 0 (x)
        and substitute to remove x from the other equations.

        0 = 0 + (-a*e/d + b)*y + (-a*f/d + c)*z
        0 = -x + (-e/d)*y + (-f/d)*z
        0 = 0 + (h - e*g/d)*y + (i - f*g/d)*z
        Nr   z'Tried to pivot about zero-valued entry.)ZeroDivisionErrorr   ranger-   )r   r   r   r|   Mijr1   rows          r   r   zLRASolver._pivot  s    T adGQq!tWa1g	1c!8#$MNNFFHQT7(3,!Q$$ 	<Caxc1fI#q&	AadG(;;#q&		< r   N)F)FF)r   r   r   r   rA   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r      sb    
: kX kXZ+=~(T(T	]Q~$. 2 2r   r   c                 >   t        | t              r| t        d      fS t        | t              r| j                  }n| g}g g }}|D ]H  }t        |      }t        |j                        dk(  r|j                  |       8|j                  |       J t        | t        | fS )z
    Example
    =======

    >>> from sympy.logic.algorithms.lra_theory import _sep_const_coeff
    >>> from sympy.abc import x, y
    >>> _sep_const_coeff(2*x)
    (x, 2)
    >>> _sep_const_coeff(2*x + 3*y)
    (2*x + 3*y, 1)
    rH   r   )r!   r
   r   r	   argsr,   rc   rR   )ru   coeffsr~   rx   r   s        r   ra   ra     s     $WQZ$RC AJq~~!LLOJJqM 9c5k!!r   c                 @    t        | t              s| gS | j                  S r    )r!   r
   r   )ru   s    r   rb   rb     s    dC v99r   c                     t        | t              r| j                  }n| g}g g }}|D ]=  }t        |j                        dk(  r|j                  |       -|j                  |       ? t        |      t        |      fS )z
    Example
    =======

    >>> from sympy.logic.algorithms.lra_theory import _sep_const_terms
    >>> from sympy.abc import x, y
    >>> _sep_const_terms(2*x + 3*y + 2)
    (2*x + 3*y, 2)
    r   )r!   r
   r   r,   rc   rR   rg   )ru   rz   r~   rx   ts        r   r`   r`     sr     $		RC q~~!#LLOJJqM	
 s8SZr   c                 X   t        | j                  j                        dk(  r"t        | j                  j                        dk(  s| S | j                  t
        j                  k(  r| j                  | j                  k  }n | j                  t
        j                  k(  r| j                  | j                  kD  }n| j                  t
        j                  k(  r| j                  | j                  k  }n| j                  t
        j                  k(  r| j                  | j                  k\  }n{| j                  t
        j                  k(  r!t        | j                  | j                        }n=| j                  t
        j                  k(  r t        | j                  | j                        }dk(  s|dk(  r|S y)z?
    Simplify binary relation to True / False if possible.
    r   TFN)r,   rV   rc   rX   rT   r   r^   r\   r]   r[   r_   r   ner   )binrelr   s     r   rZ   rZ     s    

''(A-#fjj6M6M2NRS2S!$$jj6::%	ADD	 jj6::%	ADD	 jjFJJ&	ADD	 jjFJJ&	ADD	 VZZ(	ADD	 VZZ(
d{cUl
r   c                   V    e Zd ZdZddZed        Zed        Zd Zd Z	d Z
d	 Zd
 Zy)re   zc
    Represents an upper or lower bound or an equality between a symbol
    and some constant.
    Nc                     |dvr|dv sJ || _         t        |t              r#|d   dk7  }|r||k(  sJ |d   | _        || _        n|| _        || _        |s|nd | _        || _        || _        | j                  J y )N)TFrH   r   )r~   r!   tupler&   r   r   r   )r9   r~   rx   r   r   r   rI   s          r   rA   zBoundary.__init__  s    =(},,, eU#aAAF{"{qDJDKDJ DK"*U
 {{&&&r   c                     | j                   rdnd}t        | | j                  d   d| j                  | j                  d   dk7        }|dk  r|j	                         }||fS )Nr   rH   r   T)r   re   r   r   r   r~   r   r'   s      r   r   zBoundary.from_upper.  sZ    &&bAS#))A,c.?.?1QRARS7A#vr   c                     | j                   rdnd}t        | | j                  d   d| j                  | j                  d   dk7        }|dk  r|j	                         }||fS )Nr   rH   r   F)r   re   r   r   r   r   s      r   r   zBoundary.from_lower6  sZ    &&bAS#))A,s/@/@#))A,RSBST7A#vr   c                     t        | j                  | j                  | j                   | j                  | j
                         S r    )re   r~   r&   r   r   r   r9   s    r   r   zBoundary.get_negated>  s0    $**$**ndmmQUQ\Q\_]]r   c                    | j                   r*t        | j                  j                  | j                        S | j                  r/| j
                  r#| j                  j                  | j                  k  S | j                  s/| j
                  r#| j                  j                  | j                  kD  S | j                  r#| j                  j                  | j                  k  S | j                  j                  | j                  k\  S r    )r   r   r~   r&   r   r   r  s    r   get_inequalityzBoundary.get_inequalityA  s    ==dhhllDJJ//ZZDKK88<<$**,,88<<$**,,ZZ88<<4::--88<<4::--r   c                 R    t        dt        | j                               z   dz         S )NzBoundry())reprr  r  s    r   __repr__zBoundary.__repr__M  s%    Jd&9&9&;!<<sBCCr   c                     |j                   |j                  |j                  |j                  |j                  f}| j                   | j                  | j                  | j                  | j                  f|k(  S r    )r~   r&   r   r   r   r9   others     r   __eq__zBoundary.__eq__P  sQ    EKKu{{ENNS$**dkk4::t}}MQVVVr   c                     t        | j                  | j                  | j                  | j                  | j
                  f      S r    )hashr~   r&   r   r   r   r  s    r   __hash__zBoundary.__hash__T  s,    TXXtzz4;;

DMMRSSr   r    )r   r   r   r   rA   r   r   r   r   r  r  r  r  r   r   r   re   re     sQ    '(    ^
.DWTr   re   c                   F    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zy)r   zX
    Represents a rational plus or minus some amount
    of arbitrary small deltas.
    c                     ||f| _         y r    r@   )r9   rationalr   s      r   rA   zLRARational.__init__]  s    &
r   c                 4    | j                   |j                   k  S r    r  r	  s     r   __lt__zLRARational.__lt__`  s    zzEKK''r   c                 4    | j                   |j                   k  S r    r  r	  s     r   __le__zLRARational.__le__c      zzU[[((r   c                 4    | j                   |j                   k(  S r    r  r	  s     r   r  zLRARational.__eq__f  r  r   c                     t        | j                  d   |j                  d   z   | j                  d   |j                  d   z         S Nr   rH   r   r@   r	  s     r   __add__zLRARational.__add__i  :    4::a=5;;q>94::a=5;;WX>;YZZr   c                     t        | j                  d   |j                  d   z
  | j                  d   |j                  d   z
        S r  r  r	  s     r   __sub__zLRARational.__sub__l  r  r   c                 ~    t        |t              rJ t        | j                  d   |z  | j                  d   |z        S r  )r!   r   r@   r	  s     r   __mul__zLRARational.__mul__o  s9    e[1114::a=50$**Q-%2GHHr   c                      | j                   |   S r    r  )r9   indexs     r   __getitem__zLRARational.__getitem__s  s    zz%  r   c                 ,    t        | j                        S r    )r  r@   r  s    r   r  zLRARational.__repr__v  s    DJJr   N)r   r   r   r   rA   r  r  r  r  r  r!  r$  r  r   r   r   r   r   X  s7    '())[[I! r   r   c                   (    e Zd ZdZd Zd Zd Zd Zy)rd   zK
    Object to keep track of upper and lower bounds
    on `self.var`.
    c                     t        t        d      d      | _        d| _        d| _        t        t        d       d      | _        d| _        d| _        t        dd      | _        || _	        d | _
        y )Nr   r   F)r   r   r   r   r   r   r   r   r   r~   rj   r   s     r   rA   zLRAVariable.__init__  sd     uq1
"# %,2
"#!!A&r   c                 ,    t        | j                        S r    )r  r~   r  s    r   r  zLRAVariable.__repr__      DHH~r   c                 V    t        |t              sy|j                  | j                  k(  S )NF)r!   rd   r~   r	  s     r   r  zLRAVariable.__eq__  s"    %-yyDHH$$r   c                 ,    t        | j                        S r    )r  r~   r  s    r   r  zLRAVariable.__hash__  r)  r   N)r   r   r   r   rA   r  r  r  r   r   r   rd   rd   z  s    	%
r   rd   N)-r   sympy.solvers.solvesetr   r   r   sympy.assumptionsr   sympy.assumptions.assumer   sympy.assumptions.askr   
sympy.corer   sympy.core.mulr	   sympy.core.addr
   sympy.core.relationalr   r   sympy.core.sympifyr   sympy.core.singletonr   sympy.core.numbersr   r   r   	Exceptionr   r_   r\   r^   r]   r[   rU   r   r   ra   rb   r`   rZ   re   r   rd   r   r   r   <module>r8     s   rf 7 $ ' 5 #    ( & " + 'Y  addADD!$$- n nb"< 02@T @TF   D r   