o
    8Va                     @   sB  d 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
mZmZmZ ddlmZ ddlmZ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m Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& dd Z'dd Z(dd Z)d)ddZ*dd Z+dd Z,dej-dfddZ.d d! Z/d*d"d#Z0d$d% Z1g fd&d'Z2d(S )+z<Tools for solving inequalities and systems of inequalities.     )SymbolDummysympify)iterable)factor_terms)
RelationalEqGeLt)Interval)	FiniteSetUnionEmptySetIntersection)S)
expand_mul)AbsAnd)PolyPolynomialErrorparallel_poly_from_expr)_nsort)sift)
filldedentc              	   C   s  t | ts	td|  jr.t|  d|}|tju rtjgS |tj	u r(tj
gS td| | jddg }}|dkrN|D ]\}}t||}|| q=|S |dkrrtj}|tjdfg D ]\}	}t||	d	d	}|| |	}q]|S |  dkr{d}
nd
}
d\}}|dkrd}n|dkrd
}n|dkrd\}}n|dkrd\}}ntd| tjd	}	}t|D ]I\}}|d r|
|kr|dt||	| | |
 || }
}	}q|
|kr|s|dt||	d	| |d	}	}q|
|kr|r|dt|| q|
|kr|dttj|	d	| |S )a@  Solve a polynomial inequality with rational coefficients.

    Examples
    ========

    >>> from sympy import Poly
    >>> from sympy.abc import x
    >>> from sympy.solvers.inequalities import solve_poly_inequality

    >>> solve_poly_inequality(Poly(x, x, domain='ZZ'), '==')
    [{0}]

    >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '!=')
    [Interval.open(-oo, -1), Interval.open(-1, 1), Interval.open(1, oo)]

    >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '==')
    [{-1}, {1}]

    See Also
    ========
    solve_poly_inequalities
    z8For efficiency reasons, `poly` should be a Poly instancer   %could not determine truth value of %sF)Zmultiple==!=   T)NF><>=)r   T<=)r   Tz'%s' is not a valid relation   )
isinstancer   
ValueErroras_expr	is_numberr   r   trueRealsfalser   NotImplementedErrorZ
real_rootsr   appendNegativeInfinityInfinityZLCreversedinsert)Zpolyreltreals	intervalsroot_intervalleftrightsignZeq_signZequalZ
right_openZmultiplicity r<   </usr/lib/python3/dist-packages/sympy/solvers/inequalities.pysolve_poly_inequality   sx   




0
)


r>   c                 C   s   ddl m} |dd | D  S )a  Solve polynomial inequalities with rational coefficients.

    Examples
    ========

    >>> from sympy.solvers.inequalities import solve_poly_inequalities
    >>> from sympy.polys import Poly
    >>> from sympy.abc import x
    >>> solve_poly_inequalities(((
    ... Poly(x**2 - 3), ">"), (
    ... Poly(-x**2 + 1), ">")))
    Union(Interval.open(-oo, -sqrt(3)), Interval.open(-1, 1), Interval.open(sqrt(3), oo))
    r   )r   c                 S   s   g | ]}t | D ]}|qqS r<   )r>   ).0psr<   r<   r=   
<listcomp>   s    z+solve_poly_inequalities.<locals>.<listcomp>)sympyr   )Zpolysr   r<   r<   r=   solve_poly_inequalitiesp   s   rD   c                 C   s   t j}| D ]i}|s
qtt jt jg}|D ]O\\}}}t|| |}t|d}g }	|D ]}
|D ]}|
|}|t jur?|	| q.q*|	}g }	|D ]}|D ]}||8 }qK|t jur\|	| qG|	}|sc nq|D ]}||}qfq|S )aa  Solve a system of rational inequalities with rational coefficients.

    Examples
    ========

    >>> from sympy.abc import x
    >>> from sympy import Poly
    >>> from sympy.solvers.inequalities import solve_rational_inequalities

    >>> solve_rational_inequalities([[
    ... ((Poly(-x + 1), Poly(1, x)), '>='),
    ... ((Poly(-x + 1), Poly(1, x)), '<=')]])
    {1}

    >>> solve_rational_inequalities([[
    ... ((Poly(x), Poly(1, x)), '!='),
    ... ((Poly(-x + 1), Poly(1, x)), '>=')]])
    Union(Interval.open(-oo, 0), Interval.Lopen(0, 1))

    See Also
    ========
    solve_poly_inequality
    r   )	r   r   r   r.   r/   r>   	intersectr-   union)eqsresult_eqsZglobal_intervalsnumerdenomr2   Znumer_intervalsZdenom_intervalsr5   Znumer_intervalZglobal_intervalr8   Zdenom_intervalr<   r<   r=   solve_rational_inequalities   s@   






rL   Tc              
      s  d}g }| r	t jnt j}| D ]}g }|D ]}t|tr |\}}	n|jr.|j|j |j}}	n|d}}	|t j	u rCt j
t jd}
}}	n|t ju rSt jt jd}
}}	n|  \}
}zt|
|f \\}
}}W n tyu   ttdw |jjs|
 | d}
}}|j }|js|js|
| }t|d|	}|t| ddM }q||
|f|	f q|r|| q|r|t|M }t fdd|D g}||8 }|s|r| }|r| }|S )	a8  Reduce a system of rational inequalities with rational coefficients.

    Examples
    ========

    >>> from sympy import Symbol
    >>> from sympy.solvers.inequalities import reduce_rational_inequalities

    >>> x = Symbol('x', real=True)

    >>> reduce_rational_inequalities([[x**2 <= 0]], x)
    Eq(x, 0)

    >>> reduce_rational_inequalities([[x + 2 > 0]], x)
    -2 < x
    >>> reduce_rational_inequalities([[(x + 2, ">")]], x)
    -2 < x
    >>> reduce_rational_inequalities([[x + 2]], x)
    Eq(x, -2)

    This function find the non-infinite solution set so if the unknown symbol
    is declared as extended real rather than real then the result may include
    finiteness conditions:

    >>> y = Symbol('y', extended_real=True)
    >>> reduce_rational_inequalities([[y + 2 > 0]], y)
    (-2 < y) & (y < oo)
    Tr   z
                    only polynomials and rational functions are
                    supported in this context.
                    Fr   )
relationalc                    s6   g | ]}|D ]\\}}}|  r||jfd fqqS )r   )hasZone)r?   indr7   genr<   r=   rB     s
    z0reduce_rational_inequalities.<locals>.<listcomp>)r   r*   r   r%   tupleZis_Relationallhsrhsrel_opr)   ZeroOner+   Ztogetheras_numer_denomr   r   r   domainZis_ExactZto_exactZ	get_exactZis_ZZZis_QQr   solve_univariate_inequalityr-   rL   Zevalfas_relational)exprsrS   rM   exactrG   Zsolution_exprsrI   exprr2   rJ   rK   Zoptr[   Zexcluder<   rR   r=   reduce_rational_inequalities   sZ   








rb   c                    s   |j du rttd fdd  | }ddd}g }|D ]"\} }|| vr/t| d|} n	t|  d|| } || g|  qt||S )	a  Reduce an inequality with nested absolute values.

    Examples
    ========

    >>> from sympy import Abs, Symbol
    >>> from sympy.solvers.inequalities import reduce_abs_inequality
    >>> x = Symbol('x', real=True)

    >>> reduce_abs_inequality(Abs(x - 5) - 3, '<', x)
    (2 < x) & (x < 8)

    >>> reduce_abs_inequality(Abs(x + 2)*3 - 13, '<', x)
    (-19/3 < x) & (x < 7/3)

    See Also
    ========

    reduce_abs_inequalities
    Fzr
            can't solve inequalities with absolute values containing
            non-real variables.
            c           
         s*  g }| j s| jr:| j}| jD ])} |}|s|}qg }|D ]\} }|D ]\}}||| ||| f q#q|}q|S | jr^| j}	|	jsGtd | j	}|D ]\} }|| |	 |f qN|S t
| tr | jd }|D ]\} }|| |t| dg f ||  |t| dg f ql|S | g fg}|S )Nz'Only Integer Powers are allowed on Abs.r   )Zis_AddZis_Mulfuncargsr-   is_Powexp
is_Integerr&   baser%   r   r	   r
   )
ra   r^   opargr`   rd   condsZ_exprZ_condsrP   _bottom_up_scanr<   r=   rm   :  s<   




z.reduce_abs_inequality.<locals>._bottom_up_scanr    r"   )r!   r#   r   )is_extended_real	TypeErrorr   keysr   r-   rb   )ra   r2   rS   r^   mappinginequalitiesrk   r<   rl   r=   reduce_abs_inequality  s   
'

rs   c                    s   t  fdd| D  S )a>  Reduce a system of inequalities with nested absolute values.

    Examples
    ========

    >>> from sympy import Abs, Symbol
    >>> from sympy.solvers.inequalities import reduce_abs_inequalities
    >>> x = Symbol('x', extended_real=True)

    >>> reduce_abs_inequalities([(Abs(3*x - 5) - 7, '<'),
    ... (Abs(x + 25) - 13, '>')], x)
    (-2/3 < x) & (x < 4) & (((-oo < x) & (x < -38)) | ((-12 < x) & (x < oo)))

    >>> reduce_abs_inequalities([(Abs(x - 4) + Abs(3*x - 5) - 7, '<')], x)
    (1/2 < x) & (x < 4)

    See Also
    ========

    reduce_abs_inequality
    c                    s   g | ]
\}}t || qS r<   )rs   )r?   ra   r2   rR   r<   r=   rB     s    z+reduce_abs_inequalities.<locals>.<listcomp>r   )r^   rS   r<   rR   r=   reduce_abs_inequalitiesq  s   rt   Fc           .         s  ddl m} ddlm}m}m} ddlm}	 ddlm	}
m
} |tjdu r,ttd|tjurEtd|d|}|rC|}|S 	 }|}jdu r[tj}|sV|S ||S jd	u r}td
ddz	|iW n ty|   ttdw d	}tju r|}ntju rtj}njj }||}|tjkrt|}|d}|tju r|}nm|tju rtj}nd|d	ur!|||}j}|dks|dkr|j dr|}n)|j!dstj}n|dks|dkr|j!dr|}n|j dstj}|j!|j }}|| tj"u r!t#d|dd$|}|}|d	u r|% \}}z|j&vr=t'|j&dkr=t(|
||}|d	u rJt(W n t(tfyc   ttd)t*d w t|  fdd}g }|	D ]}|+|
|| qw|s| |}djv ojdk}zgt,|j-t.|j!|j  }t.|| t/|  t#|j!|j |j!|v|j |v}t0dd |D rt1|ddd }n,t2|dd }|d	 rtz|d }t'|dkrt/t3|}W n
 ty   tw W n ty   tdw tj} | tjkrd}!t. }"z|| |}#t4|#t#sF|#D ]}$|$|vrC||$rC|$jrC|"t.|$7 }"q-no|#j!|#j }%}&t1|t.|& D ]S}$||%}'|%|&kr||$}(t5|%|$})|)|vr|)jr||)r|'r|(r|"t#|%|$7 }"n |'r|"t#6|%|$7 }"n|(r|"t#7|%|$7 }"n|"t#8|%|$7 }"|$}%qU|D ]	}*|"t.|*8 }"qW n ty   tj}"d}!Y nw t4|"trt(td)||f | $|"} tjg}+|j!}%|%|v r||%r|%j9r|+:t.|% |D ]?},|,}&|t5|%|&r|+:t#|%|&dd |,|v r|;|, n|,|v r-|;|, ||,}-n|}-|-r9|+:t.|, |&}%q|j }&|&|v rU||&rU|&j9rU|+:t.|& |t5|%|&rf|+:t#8|%|& | tjkrw|!rw| $|}nt<t=|+ | |)|}|s|S ||S ) a  Solves a real univariate inequality.

    Parameters
    ==========

    expr : Relational
        The target inequality
    gen : Symbol
        The variable for which the inequality is solved
    relational : bool
        A Relational type output is expected or not
    domain : Set
        The domain over which the equation is solved
    continuous: bool
        True if expr is known to be continuous over the given domain
        (and so continuous_domain() doesn't need to be called on it)

    Raises
    ======

    NotImplementedError
        The solution of the inequality cannot be determined due to limitation
        in :func:`sympy.solvers.solveset.solvify`.

    Notes
    =====

    Currently, we cannot solve all the inequalities due to limitations in
    :func:`sympy.solvers.solveset.solvify`. Also, the solution returned for trigonometric inequalities
    are restricted in its periodic interval.

    See Also
    ========

    sympy.solvers.solveset.solvify: solver returning solveset solutions with solve's output API

    Examples
    ========

    >>> from sympy.solvers.inequalities import solve_univariate_inequality
    >>> from sympy import Symbol, sin, Interval, S
    >>> x = Symbol('x')

    >>> solve_univariate_inequality(x**2 >= 4, x)
    ((2 <= x) & (x < oo)) | ((x <= -2) & (-oo < x))

    >>> solve_univariate_inequality(x**2 >= 4, x, relational=False)
    Union(Interval(-oo, -2), Interval(2, oo))

    >>> domain = Interval(0, S.Infinity)
    >>> solve_univariate_inequality(x**2 >= 4, x, False, domain)
    Interval(2, oo)

    >>> solve_univariate_inequality(sin(x) > 0, x, relational=False)
    Interval.open(0, pi)

    r   )im)continuous_domainperiodicityfunction_rangedenoms)solvifysolvesetFz|
        Inequalities in the complex domain are
        not supported. Try the real domain by
        setting domain=S.Reals)rM   
continuousNrS   TZextended_realz
                When gen is real, the relational has a complex part
                which leads to an invalid comparison like I < 0.
                r!   r#   r    r"   r   z
                    The inequality, %s, cannot be solved using
                    solve_univariate_inequality.
                    xc                    s     t| }z|d}W n ty   tj}Y nw |tjtjfv r'|S |jdu r/tjS |d}|j	r=|dS t
d| )Nr   Fr$   z!relationship did not evaluate: %s)subsr   rc   ro   r   r+   r)   rn   rP   Zis_comparabler,   )r   vrZ
expanded_era   rS   r<   r=   valid&  s    



z*solve_univariate_inequality.<locals>.valid=r   c                 s   s    | ]}|j V  qd S N)r(   )r?   r   r<   r<   r=   	<genexpr>Q  s    z.solve_univariate_inequality.<locals>.<genexpr>)	separatedc                 S   s   | j S r   rn   )r   r<   r<   r=   <lambda>T  s    z-solve_univariate_inequality.<locals>.<lambda>z'sorting of these roots is not supportedz
                        %s contains imaginary parts which cannot be
                        made 0 for any value of %s satisfying the
                        inequality, leading to relations like I < 0.
                        )>rC   ru   Zsympy.calculus.utilrv   rw   rx   sympy.solvers.solversrz   Zsympy.solvers.solvesetr{   r|   Z	is_subsetr   r*   r,   r   r\   intersectionr]   rn   r   r   xreplacero   r)   r+   rU   rV   rX   r   rc   rW   supinfr/   r   rE   rZ   free_symbolslenr&   r   r   extendsetboundaryr   listallr   r   sortedr%   _ptZRopenZLopenopenZ	is_finiter-   remover   r   ).ra   rS   rM   r[   r}   ru   rv   rw   rx   rz   r{   r|   rvZ_genZ_domaineZperiodconstZfranger2   r   r   rP   rQ   Zsolnsr   ZsingularitiesZ	include_xZdiscontinuitiesZcritical_pointsr4   ZsiftedZ	make_realcheckZim_solazstartendZvalid_startZvalid_zptrA   Zsol_setsr   Z_validr<   r   r=   r\     sl  :
























r\   c                 C   s   | j s|j s| | d }|S | j r|j rtj}|S | j r!| jdu s)|j r-|jdu r-td|j r3|js9| j r>| jr>|| } }|j rZ| jrJ| d }|S | jrT| tj }|S | d }|S | j rt|jrg|tj }|S |jrp|d }|S |d }|S )z$Return a point between start and endr$   Nz,cannot proceed with unsigned infinite valuesr   )Zis_infiniter   rX   Zis_extended_positiver&   Zis_extended_negativeZHalf)r   r   r   r<   r<   r=   r     sH   



r   c                 C   sh  ddl m} || jvr| S | j|kr| j} | j|kr"|| jjvr"| S dd }d}tj}| j| j }z t||}|	 dkrF| 
| d}n
|sP|	 dkrPtW n ttfy   |sz	t| gg|}W n tys   t| |}Y nw || ||}	|	tju r||||tju r|||k d}|| || }
|
tju r|||| tju r|| |k d}||| kd}|tju r|	tju r||kn||k }|
tjurt| |k |}nt|}Y nw g }|du r| }d}|j|dd\}}||8 }||8 }t|}|j|d	d\}}|jd	ks&|j|j  krdu r+n n| jd
vr+|}tj}|| }|jr:| 
||}n| j
||}|| j|| jB }||}|| D ]*}tt|d||d}t|tr||j|kr|||||jtju r|||  qS| |fD ]'}||||tju r|| ||tjur|||u r||k n||k  q|| t| S )a  Return the inequality with s isolated on the left, if possible.
    If the relationship is non-linear, a solution involving And or Or
    may be returned. False or True are returned if the relationship
    is never True or always True, respectively.

    If `linear` is True (default is False) an `s`-dependent expression
    will be isolated on the left, if possible
    but it will not be solved for `s` unless the expression is linear
    in `s`. Furthermore, only "safe" operations which don't change the
    sense of the relationship are applied: no division by an unsigned
    value is attempted unless the relationship involves Eq or Ne and
    no division by a value not known to be nonzero is ever attempted.

    Examples
    ========

    >>> from sympy import Eq, Symbol
    >>> from sympy.solvers.inequalities import _solve_inequality as f
    >>> from sympy.abc import x, y

    For linear expressions, the symbol can be isolated:

    >>> f(x - 2 < 0, x)
    x < 2
    >>> f(-x - 6 < x, x)
    x > -3

    Sometimes nonlinear relationships will be False

    >>> f(x**2 + 4 < 0, x)
    False

    Or they may involve more than one region of values:

    >>> f(x**2 - 4 < 0, x)
    (-2 < x) & (x < 2)

    To restrict the solution to a relational, set linear=True
    and only the x-dependent portion will be isolated on the left:

    >>> f(x**2 - 4 < 0, x, linear=True)
    x**2 < 4

    Division of only nonzero quantities is allowed, so x cannot
    be isolated by dividing by y:

    >>> y.is_nonzero is None  # it is unknown whether it is 0 or not
    True
    >>> f(x*y < 1, x)
    x*y < 1

    And while an equality (or inequality) still holds after dividing by a
    non-zero quantity

    >>> nz = Symbol('nz', nonzero=True)
    >>> f(Eq(x*nz, 1), x)
    Eq(x, 1/nz)

    the sign must be known for other inequalities involving > or <:

    >>> f(x*nz <= 1, x)
    nz*x <= 1
    >>> p = Symbol('p', positive=True)
    >>> f(x*p <= 1, x)
    x <= 1/p

    When there are denominators in the original expression that
    are removed by expansion, conditions for them will be returned
    as part of the result:

    >>> f(x < x*(2/x - 1), x)
    (x < 1) & Ne(x, 0)
    r   ry   c                 S   sJ   z|  ||}|tju r|W S |dvrW d S |W S  ty$   tj Y S w )NTF)r   r   ZNaNro   )ierA   rO   r   r<   r<   r=   classify*  s   

z#_solve_inequality.<locals>.classifyNr   T)Zas_AddF)r   r   )linear)r   rz   r   rV   r0   rU   r   r/   r   Zdegreerc   r'   r,   r   rb   r\   r)   r+   r   r   Zas_independentr   Zis_zeroZis_negativeZis_positiverW   rY   _solve_inequalityr   r%   r-   )r   rA   r   rz   r   r   Zoora   r@   ZokooZoknoork   r   rV   bZaxZefr   Zbeginning_denomsZcurrent_denomsrQ   crO   r<   r<   r=   r     s   J







 
r   c                    sb  i i }}g }| D ]x}|j |j}}|t}t|dkr"|  n"|j|@ }	t|	dkr>|	  |tt	|d|  q	t
td| rU| g ||f q	| fdd}
|
rutdd |
D ru| g ||f q	|tt	|d|  q	g }g }| D ]\ }|t|g  q| D ]\ }|t|  qt|| |  S )Nr   r   zZ
                    inequality has more than one symbol of interest.
                    c                    s    |   o| jp| jo| jj S r   )rN   Zis_Functionre   rf   rg   )urR   r<   r=   r     s   
z&_reduce_inequalities.<locals>.<lambda>c                 s   s    | ]}t |tV  qd S r   )r%   r   r?   rO   r<   r<   r=   r         z'_reduce_inequalities.<locals>.<genexpr>)rU   rW   Zatomsr   r   popr   r-   r   r   r,   r   Zis_polynomial
setdefaultfindr   itemsrb   rt   r   )rr   symbolsZ	poly_partZabs_partotherZ
inequalityra   r2   genscommonZ
componentsZpoly_reducedZabs_reducedr^   r<   rR   r=   _reduce_inequalities  s4   




r   c                    sJ  t | s| g} dd | D } t jdd | D  }t |s |g}t|p%||@ }tdd |D r7ttddd |D   fd	d| D }  fd
d|D }g }| D ]<}t|trj||j	
 |j
  d}n	|dvrst|d}|dkrxqT|dkrtj  S |j	jrtd| || qT|} ~t| |}|dd   D S )aZ  Reduce a system of inequalities with rational coefficients.

    Examples
    ========

    >>> from sympy.abc import x, y
    >>> from sympy.solvers.inequalities import reduce_inequalities

    >>> reduce_inequalities(0 <= x + 3, [])
    (-3 <= x) & (x < oo)

    >>> reduce_inequalities(0 <= x + y*2 - 1, [x])
    (x < oo) & (x >= 1 - 2*y)
    c                 S   s   g | ]}t |qS r<   )r   r   r<   r<   r=   rB     s    z'reduce_inequalities.<locals>.<listcomp>c                 S   s   g | ]}|j qS r<   )r   r   r<   r<   r=   rB     s    c                 s   s    | ]}|j d u V  qdS )FNr   r   r<   r<   r=   r     r   z&reduce_inequalities.<locals>.<genexpr>zP
            inequalities cannot contain symbols that are not real.
            c                 S   s&   i | ]}|j d u r|t|jddqS )NTr~   )rn   r   namer   r<   r<   r=   
<dictcomp>  s    
z'reduce_inequalities.<locals>.<dictcomp>c                    s   g | ]}|  qS r<   r   r   Zrecastr<   r=   rB         c                    s   h | ]}|  qS r<   r   r   r   r<   r=   	<setcomp>  r   z&reduce_inequalities.<locals>.<setcomp>r   r   TFr   c                 S   s   i | ]\}}||qS r<   r<   )r?   kr   r<   r<   r=   r     r   )r   r   rF   anyro   r   r%   r   rc   rU   r'   rV   r   r   r+   r(   r,   r-   r   r   r   )rr   r   r   ZkeeprO   r   r<   r   r=   reduce_inequalities  sB   



r   N)T)F)3__doc__Z
sympy.corer   r   r   Zsympy.core.compatibilityr   Zsympy.core.exprtoolsr   Zsympy.core.relationalr   r   r	   r
   Z
sympy.setsr   Zsympy.sets.setsr   r   r   r   Zsympy.core.singletonr   Zsympy.core.functionr   Zsympy.functionsr   Zsympy.logicr   Zsympy.polysr   r   r   Zsympy.polys.polyutilsr   Zsympy.utilities.iterablesr   Zsympy.utilities.miscr   r>   rD   rL   rb   rs   rt   r*   r\   r   r   r   r   r<   r<   r<   r=   <module>   s:    \
CZR  .
! .3