K ildZddlmZddlmZmZmZddlmZm Z ddl m Z ddl m Z mZmZmZddlmZddlmZdd lmZdd lmZdd lmZmZdd lmZmZdd lm Z m!Z!ddl"m#Z#ddl$m%Z%ddl&m'Z'm(Z(ddl)m*Z*ddl+m,Z,m-Z-m.Z.ddl/m0Z0m1Z1ddl2m3Z3dZ4eGddeZ5Gdde5Z6Gdde6e'Z7Gdde6e'Z8e7Z9e8Z:e9e(_9e:e(_:de,e;<Gd d!ee5Z<Gd"d#e%e<Z=Gd$d%e%e<Z>Gd&d'e<Z?Gd(d)e<Z@Gd*d+e<ZAGd,d-e<ZBGd.d/e<ZCGd0d1e<ZDGd2d3e<ZEGd4d5e<ZFGd6d7e<ZGd8ZHd9ZId:ZJd;ZKd<ZLd=ZMdld>ZNdld?ZOdmd@ZPdmdAZQdBZRdldCZSdDZTdEZUdFZVdGZWdHZXdIZYdJZZe1Z[dldKZ\dLZ]dMZ^dNZ_dOZ`dPZadQZbdRZcdSZddTZedndVZfdWZgdndXZhdYZidZZjd[Zkd\Zld]Zmd^Zndod_Zod`ZpdaZqdbZr dpdcZsddZtdeZuedfZvedgZwedhZxediZydjZze=e>e@eAeBe?eCeFfZ{dkZ|yU)qz" Boolean algebra module for SymPy ) annotations) TYPE_CHECKINGoverloadAny)IterableMapping) defaultdict)chain combinationsproduct permutations)Add)Basic)cacheit)Tuple)sympify_method_argssympify_return) Application Derivative) BooleanKind NumberKind)Number) LatticeOp) SingletonS)ordered)_sympy_converter_sympifysympify)siftibin) filldedentcddlm}|dk(rtS|dk(rtSt ||r|j }||S|rtStSt |t r|Std|z)aLike ``bool``, return the Boolean value of an expression, e, which can be any instance of :py:class:`~.Boolean` or ``bool``. Examples ======== >>> from sympy import true, false, nan >>> from sympy.logic.boolalg import as_Boolean >>> from sympy.abc import x >>> as_Boolean(0) is false True >>> as_Boolean(1) is true True >>> as_Boolean(x) x >>> as_Boolean(2) Traceback (most recent call last): ... TypeError: expecting bool or Boolean, not `2`. >>> as_Boolean(nan) Traceback (most recent call last): ... TypeError: expecting bool or Boolean, not `nan`. r)SymbolTFz$expecting bool or Boolean, not `%s`.)sympy.core.symbolr$truefalse isinstanceis_zeroBoolean TypeError)er$zs Y/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/logic/boolalg.py as_Booleanr/si4)Dy Ez !V II 9Hu#t#!W :Q> ??ceZdZdZdZeZerMddZe dddZ e dddZ e ddZ e dddZ e ddd Z e d d Z d d!d Z d"d Z e d ge dZeZe d ge dZeZdZe d ge dZe d ge dZeZeZe d ge dZeZdZd#dZdZedZdZy)$r*zDA Boolean object is an object for which logic operations make sense.cyNr2clsargss r.__new__zBoolean.__new__N r0Ncyr4r2selfarg1arg2s r.subsz Boolean.subsQsgjr0c yr4r2r<r=r>kwargss r.r?z Boolean.subsSs Br0cyr4r2r;s r.r?z Boolean.subsUsUXr0c yr4r2rAs r.r?z Boolean.subsWsrur0c yr4r2rAs r.r?z Boolean.subsYsz}r0c yr4r2rAs r.r?z Boolean.subs[s^ar0c yr4r2rAs r.r?z Boolean.subs^ r0c yr4r2r<rBs r.simplifyzBoolean.simplifybr9r0)otherr*ct||Sr4Andr<rLs r.__and__zBoolean.__and__e4r0ct||Sr4)OrrPs r.__or__zBoolean.__or__ks$r0ct|S)zOverloading for ~)Notr<s r. __invert__zBoolean.__invert__qs 4yr0ct||Sr4ImpliesrPs r. __rshift__zBoolean.__rshift__ustU##r0ct||Sr4r[rPs r. __lshift__zBoolean.__lshift__ysud##r0ct||Sr4)XorrPs r.__xor__zBoolean.__xor__rRr0cddlm}ddlm}|j |s|j |r t d|j |j k(xr|tt|| S)a Returns ``True`` if the given formulas have the same truth table. For two formulas to be equal they must have the same literals. Examples ======== >>> from sympy.abc import A, B, C >>> from sympy import And, Or, Not >>> (A >> B).equals(~B >> ~A) True >>> Not(And(A, B, C)).equals(And(Not(A), Not(B), Not(C))) False >>> Not(And(A, Not(A))).equals(Or(B, Not(B))) False r) satisfiable Relationalzhandling of relationals) sympy.logic.inferencerdsympy.core.relationalrfhasNotImplementedErroratomsrW Equivalent)r<rLrdrfs r.equalszBoolean.equalssb$ 64 88J 599Z#8%&?@ @zz|u{{},:C 4 789 9 :r0c|Sr4r2r<rKs r.to_nnfzBoolean.to_nnf r0cxddlm}ddlm}|j}t |dk(r |j }|jturi}|j|D]w}|||dvs|j}|tjtjtjfvr|j|||<et!t#d|j%|}|j&|j&k7r|j)S|jS|jSt!d)a Rewrites Boolean expression in terms of real sets. Examples ======== >>> from sympy import Symbol, Eq, Or, And >>> x = Symbol('x', real=True) >>> Eq(x, 0).as_set() {0} >>> (x > 0).as_set() Interval.open(0, oo) >>> And(-2 < x, x < 2).as_set() Interval.open(-2, 2) >>> Or(x < -2, 2 < x).as_set() Union(Interval.open(-oo, -2), Interval.open(2, oo)) r) periodicityre)rNz as_set is not implemented for relationals with periodic solutions zGSorry, as_set has not yet been implemented for multivariate expressions)sympy.calculus.utilrsrhrf free_symbolslenpopkindrrk _eval_as_setrEmptySet UniversalSetReals as_relationalrjr"r?funcas_set) r<rsrffreexrepsrsnews r.rzBoolean.as_sets& 44   t9> Avv#J/ "A"1a( 9NN,Q^^QWW EE&'ooa&8DG$1*> 3!"" "iio88tyy(::<'++--$$& &%'56 6r0c ddlm}m}tj|j Dcgc]4}|j s|jst|||fr |j6c}Scc}w)NrEqNe) rhrrsetunionr7 is_Boolean is_Symbolr(binary_symbols)r<rris r.rzBoolean.binary_symbolssX0su{{tyy7!llakk(RH5--78 87s9A(cJddlm}|||}|durtS|durtSy)Nr)askTF)sympy.assumptionsrr&r')r< assumptionsrrets r. _eval_refinezBoolean._eval_refines,)$ $ $;K E\Lr0)r7Basic | complexreturnr*r4)r=z+Mapping[Basic | complex, Boolean | complex]r>Nonerr*)r=z3Iterable[tuple[Basic | complex, Boolean | complex]]r>rrBrrr*)r=Boolean | complexr>rrr*)r=z)Mapping[Basic | complex, Basic | complex]r>rrBrrr)r=z1Iterable[tuple[Basic | complex, Basic | complex]]r>rrBrrr)r=rr>rrBrrr)r=z;Mapping[Basic | complex, Basic | complex] | Basic | complexr>zBasic | complex | NonerBrrr)rr*T)__name__ __module__ __qualname____doc__ __slots__rryrr8rr?rKrNotImplementedrQ__rand__rU__ror__rYr]r_ __rrshift__ __rlshift__rb__rxor__rmrprpropertyrrr2r0r.r*r*DsNI D  j j  B  B X X u u } } a a15 - @C HM  )*N; < H)*N;<G)*N;$<$)*N;$<$KK)*N; < H:4/6b88 r0r*ceZdZdZdZdZdZdZdZe dZ d dZ e Z e Z e Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Zd ZeZeZeZd Zy) BooleanAtomzQ Base class of :py:class:`~.BooleanTrue` and :py:class:`~.BooleanFalse`. T c|Sr4r2r<akws r.rKzBooleanAtom.simplify r0c|Sr4r2rs r.expandzBooleanAtom.expandrr0c|Sr4r2rXs r. canonicalzBooleanAtom.canonicalrqr0Nctd)Nz(BooleanAtom not allowed in this context.)r+rPs r._noopzBooleanAtom._noopsBCCr0c*ttdNz A Boolean argument can only be used in Eq and Ne; all other relationals expect real expressions. r+r"rPs r.__lt__zBooleanAtom.__lt__  $   r0c |Sr4r2rJs r._eval_simplifyzBooleanAtom._eval_simplifyrr0r4)rrrrris_Atom _op_priorityrKrrrr__add____radd____sub____rsub____mul____rmul____pow____rpow__ __truediv__ __rtruediv____mod____rmod__ _eval_powerr__le____gt____ge__rr2r0r.rrsJGLDGHGHGHGHKLGHKF F Fr0rcDeZdZdZdZdZfdZedZdZ xZ S) BooleanTruea SymPy version of ``True``, a singleton that can be accessed via ``S.true``. This is the SymPy version of ``True``, for use in the logic module. The primary advantage of using ``true`` instead of ``True`` is that shorthand Boolean operations like ``~`` and ``>>`` will work as expected on this class, whereas with True they act bitwise on 1. Functions in the logic module will return this class when they evaluate to true. Notes ===== There is liable to be some confusion as to when ``True`` should be used and when ``S.true`` should be used in various contexts throughout SymPy. An important thing to remember is that ``sympify(True)`` returns ``S.true``. This means that for the most part, you can just use ``True`` and it will automatically be converted to ``S.true`` when necessary, similar to how you can generally use 1 instead of ``S.One``. The rule of thumb is: "If the boolean in question can be replaced by an arbitrary symbolic ``Boolean``, like ``Or(x, y)`` or ``x > 1``, use ``S.true``. Otherwise, use ``True``" In other words, use ``S.true`` only on those contexts where the boolean is being used as a symbolic representation of truth. For example, if the object ends up in the ``.args`` of any expression, then it must necessarily be ``S.true`` instead of ``True``, as elements of ``.args`` must be ``Basic``. On the other hand, ``==`` is not a symbolic operation in SymPy, since it always returns ``True`` or ``False``, and does so in terms of structural equality rather than mathematical, so it should return ``True``. The assumptions system should use ``True`` and ``False``. Aside from not satisfying the above rule of thumb, the assumptions system uses a three-valued logic (``True``, ``False``, ``None``), whereas ``S.true`` and ``S.false`` represent a two-valued logic. When in doubt, use ``True``. "``S.true == True is True``." While "``S.true is True``" is ``False``, "``S.true == True``" is ``True``, so if there is any doubt over whether a function or expression will return ``S.true`` or ``True``, just use ``==`` instead of ``is`` to do the comparison, and it will work in either case. Finally, for boolean flags, it's better to just use ``if x`` instead of ``if x is True``. To quote PEP 8: Do not compare boolean values to ``True`` or ``False`` using ``==``. * Yes: ``if greeting:`` * No: ``if greeting == True:`` * Worse: ``if greeting is True:`` Examples ======== >>> from sympy import sympify, true, false, Or >>> sympify(True) True >>> _ is True, _ is true (False, True) >>> Or(true, false) True >>> _ is true True Python operators give a boolean result for true but a bitwise result for True >>> ~true, ~True # doctest: +SKIP (False, -2) >>> true >> true, True >> True (True, 0) See Also ======== sympy.logic.boolalg.BooleanFalse cyNTr2rXs r.__bool__zBooleanTrue.__bool__msr0ctdSrhashrXs r.__hash__zBooleanTrue.__hash__ps Dzr0c6|dury|duryt||SNTFsuper__eq__r<rL __class__s r.rzBooleanTrue.__eq__ss& D= E>w~e$$r0ctSr4)r'rXs r.negatedzBooleanTrue.negatedzs r0c"tjS)z Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import true >>> true.as_set() UniversalSet )rr|rXs r.rzBooleanTrue.as_set~s~~r0 rrrrrrrrrr __classcell__rs@r.rrs2Rf% r0r) metaclasscDeZdZdZdZdZfdZedZdZ xZ S) BooleanFalsea SymPy version of ``False``, a singleton that can be accessed via ``S.false``. This is the SymPy version of ``False``, for use in the logic module. The primary advantage of using ``false`` instead of ``False`` is that shorthand Boolean operations like ``~`` and ``>>`` will work as expected on this class, whereas with ``False`` they act bitwise on 0. Functions in the logic module will return this class when they evaluate to false. Notes ====== See the notes section in :py:class:`sympy.logic.boolalg.BooleanTrue` Examples ======== >>> from sympy import sympify, true, false, Or >>> sympify(False) False >>> _ is False, _ is false (False, True) >>> Or(true, false) True >>> _ is true True Python operators give a boolean result for false but a bitwise result for False >>> ~false, ~False # doctest: +SKIP (True, -1) >>> false >> false, False >> False (True, 0) See Also ======== sympy.logic.boolalg.BooleanTrue cyNFr2rXs r.rzBooleanFalse.__bool__sr0ctdSrrrXs r.rzBooleanFalse.__hash__s E{r0c6|dury|duryt||Srrrs r.rzBooleanFalse.__eq__s& D= E>w~e$$r0ctSr4)r&rXs r.rzBooleanFalse.negateds r0c"tjS)z Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import false >>> false.as_set() EmptySet )rr{rXs r.rzBooleanFalse.as_setszzr0rrs@r.rrs1)T% r0rc|rtStSr4)r&r'rs r.rs 14%r0c~eZdZdZdZdZdZdZeZeZ eZ e dZ ddZ ddZe d Ze d Zd Zd Zy )BooleanFunctionzBoolean function is a function that lives in a boolean space It is used as base class for :py:class:`~.And`, :py:class:`~.Or`, :py:class:`~.Not`, etc. Tc t|}t|ts|jdi|S|j|j Dcgc]}|jdi|c}}t |Scc}w)Nr2)simplify_univariater(rrKrr7simplify_logic)r<rBrvrs r.rzBooleanFunction._eval_simplifysg  &"o.2;;(( ( RWWRWW=zqzz+F+= >b!!>sA0c  ddlm}||fi|S)NrrK)sympy.simplify.simplifyrK)r<rBrKs r.rKzBooleanFunction.simplifys4'''r0c*ttdrrrPs r.rzBooleanFunction.__lt__rr0c>|Dcgc] }t|c}Scc}wr4)r/)r<r7rs r.binary_check_and_simplifyz)BooleanFunction.binary_check_and_simplifys'+,! 1 ,,,sc:|j|jd|iS)NrK)_to_nnfr7ros r.rpzBooleanFunction.to_nnfst||TYY:::r0c:|j|jd|iSNdeep)_to_anfr7r<rs r.to_anfzBooleanFunction.to_anfst||TYY2T22r0cT|jdd}t}|D]}t|s|j|}|rRt ||r |j }n|f}|D]0}t ||vr|jccS|j|2s|j|||S)NrKT) getr is_literalrpr(r7rWzeroadd)r6r7rBrKargsetargrs r.rzBooleanFunction._to_nnf s::j$/ Cc?jj*c3'((C&C"A1v'"xxJJqM"  3 F|r0c|jdd}g}|D]B}|r-t|rt|tr|j |}|j |D||ddiS)NrTr remove_trueF)rrr(rWrappend)r6r7rBrnew_argsr s r.rzBooleanFunction._to_anfsgzz&$' !C!#*S#*>**$*/C OOC  ! H0%00r0cD|jddt|g|i|S)NevaluateT) setdefaultr)r<symbolsrs r.diffzBooleanFunction.diff)s'z40$88K88r0c ||jvr>ddlm}ddlm}|d||j |d|j |dfdS||j vrytjS)Nr)r Piecewisert)rtT) rrhr$sympy.functions.elementary.piecewiserr?rvrZero)r<rrrs r._eval_derivativez BooleanFunction._eval_derivative-sg ## # 0 FBtyyA !Q89 $## # 66Mr0Nr)rrrrrrrKrrrr classmethodrrprrrrrr2r0r.rrs|J"( F F F--;3&119 r0rcveZdZdZeZeZdZe r d dZ e d dZ e dZdZfdZdZd Zd d ZxZS)rOaS Logical AND function. It evaluates its arguments in order, returning false immediately when an argument is false and true if they are all true. Examples ======== >>> from sympy.abc import x, y >>> from sympy import And >>> x & y x & y Notes ===== The ``&`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise and. Hence, ``And(a, b)`` and ``a & b`` will produce different results if ``a`` and ``b`` are integers. >>> And(x, y).subs(x, 1) y Ncyr4r2r5s r.r8z And.__new__^r9r0cyr4r2rXs r.r7zAnd.argsarHr0cVtj|}tj|t}g}t }t |D]b}|jrC|j}||vr |jj|vr tgcS|j||j|d|Sr4) rrr_new_args_filterrOrr is_Relationalrrr'r r)r6r7newargsrelrcs r.r!zAnd._new_args_filteres88$?))$4e AKK8YY((C/!7NGGAJ NN1  r0cg}d}|jD]9} |j||}|dk(rtcS|dk7s)|j |;||j||t |t rEt|j}|j|rt||z }|j||j|S#t$r||}YwxYw)NFT) r7r?r+r'rr(rOrissubsetr rr<oldrr7badrold_sets r. _eval_subszAnd._eval_subsws A FF3$ Ez d A  ? HHS#  c3 #((mG%4y7* tyy$) ;C  C CCc ddlmmddlm}t |di|}t|ts|St|jfdd\}}|s|St|fdd\}}|d}|r|d } i} i} tt|D cgc]} | j| fc} d } g}g} d | vr| jd D]2\}}|j}|j|k7s||jjvrr|| vrn |t!|j|j d |\}}|j#|| |z }||| ||zkr|}n|j%| || vr%|j%|j)|| ||j|k(r:||jjvr"|j| |<|j%|"| j%|5t+t,}| D]K}| |D]A\}}|j/| }|j}|t1|j%||fCM|} d | vr| D])}|j3| |Dcgc]\}}| c}}+| Dcgc]}|j)| } }|Dcgc]}|j)| }}|j"|| z|zD cgc]} | j4c} |z}t7}t9}t;|||t<|Scc} w#t&$rYwxYwcc}}wcc}wcc}wcc} w)Nr)Equalityrf) linear_coeffsct|Sr4r(rrfs r.rz$And._eval_simplify..sjJ.Gr0Tbinaryct|Sr4r2)rr/s r.rz$And._eval_simplify..sAx)@r0measureratioct|dSNr)rwrs r.rz$And._eval_simplify..s#ad)r0rtFr)threeterm_patternsr2)rhr/rfsympy.solvers.solvesetr0rrr(rOr r7rrvrxlhsrhsrrr ValueErrorr?r listxreplacerwextendr_simplify_patterns_and_simplify_patterns_and3"_apply_patternbased_simplificationr')r<rBr0rRelnonReleqsrLr7r8rsiftedr nonlineqsrr,rmbenewresiftedkfeipatternsr<r/rfrs @@r.rzAnd._eval_simplifys<>8 W # -f -"c"I277$G"&( VI#@N U# 7OEDF'-0#2()##23#%FCIv+%zz!},GD! A a155+=+=&=1D= !#0 #AEEAEE6E BA$GDAq#$66!aRT?D&t}gaj0@@$( # 1 (!" Dy 166!T!W#56!1C1C(C"#%%Q 1 "((++,,'t,8A &q 81JJt,NN Q(//A788 ";v+< 6 &)4$!QA45 61:;2;I;-23rRWWT]3E3# /E2IKAAKKKfTVB)+461"h295EWY YU#2$ *! !$5;3Ks1L# A+L(9 L8 L>1M!M( L54L5cnddlm}||jDcgc]}|jc}Scc}w)Nr) Intersection)sympy.sets.setsrUr7r)r<rUr s r.rzzAnd._eval_as_sets(0dii@scjjl@AA@2c^t|jDcgc] }t|c}Scc}wr4)Norr7rWr<r7rBr s r._eval_rewrite_as_NorzAnd._eval_rewrite_as_Nors#3#SX3443*c^|r*tj|jd|i}t|S|Sr)rOrr7distribute_xor_over_and)r<rresults r.rz And.to_anfs, [[$))7$7F*62 2 r0r7zBoolean | boolrr*rztuple[Boolean, ...]r)rrrrr'rr&identitynargsrr8rr7rr!r,rrzr[rrrs@r.rOrO<sf4 DH E     " 8BYHB5r0rOcreZdZdZeZeZer d dZ e d dZ e dZ dZdZdZfdZd d ZxZS) rTaM Logical OR function It evaluates its arguments in order, returning true immediately when an argument is true, and false if they are all false. Examples ======== >>> from sympy.abc import x, y >>> from sympy import Or >>> x | y x | y Notes ===== The ``|`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise or. Hence, ``Or(a, b)`` and ``a | b`` will return different things if ``a`` and ``b`` are integers. >>> Or(x, y).subs(x, 0) y cyr4r2r5s r.r8z Or.__new__r9r0cyr4r2rXs r.r7zOr.argsrHr0cVg}g}tj|}|D]t}|jrU|j}||vr |jjt fd|Dr t gcS|j||j|vtj|tS)Nc3(K|] }|k( ywr4r2).0rncs r. z&Or._new_args_filter..s,1qBw,s) rrr"rranyr&rrr!rT)r6r7r#r$rr%rjs @r.r!zOr._new_args_filter s88$? AKK8YY((,,, 6M 1 NN1  ))'266r0cg}d}|jD]9} |j||}|dk(rtcS|dk7s)|j |;||j||t |t rEt|j}|j|rt||z }|j||j|S#t$r||}YwxYwr) r7r?r+r&rr(rTrr'r rr(s r.r,z Or._eval_subss A FF3$ Dy e A  ? HHS#  c2 #((mG%4y7* tyy$) ;C  r-cnddlm}||jDcgc]}|jc}Scc}w)Nr)Union)rVror7r)r<ror s r.rzzOr._eval_as_set9s()tyy9szz|9::9rWc^t|jDcgc] }t|c}Scc}wr4)Nandr7rWrZs r._eval_rewrite_as_NandzOr._eval_rewrite_as_Nand=s#$))43c#h4554r\c ddlm}m}m}|j ||}|rf|Dcic]:}||j ||j |j|j<}}|j|jdi|St |(di|}t|ts|St} t|| |dt Scc}w)Nr)LeGerr7r2)rhrtrurrkrr>r?strictrBrrr(rT_simplify_patterns_orrFr&) r<rBrtrurlegerrrrSrs r.rzOr._eval_simplify@s44zz"b! 59;01tyy155!%% !((,,;D;54==&55?? ? W # -f -"b!I(*1"h282CTK K;s?Cctdtjdz}fd|D}tj|}d|D}fd|D}t t |ddiS)Nrtc3JK|]}tj|ywr4)r r7)rijr<s r.rkzOr.to_anf..Qs9q TYY*9s #c3,K|] }t|ywr4rN)rir s r.rkzOr.to_anf..Ss*cS *sc3@K|]}r t|n|yw)r N)r)rirrs r.rkzOr.to_anf..TsBqt$!3BsrF)rangerwr7r from_iterablerarA)r<rr7s`` r.rz Or.to_anfOs^QDII*+9D9""4(*T*BTBDJ2E22r0r`rar)rrrrr&rr'rbrr8rr7rr!r,rzrrrrrrs@r.rTrTs^4 DH     77  8;6 K3r0rTc:eZdZdZdZedZdZddZddZ y) rWa Logical Not function (negation) Returns ``true`` if the statement is ``false`` or ``False``. Returns ``false`` if the statement is ``true`` or ``True``. Examples ======== >>> from sympy import Not, And, Or >>> from sympy.abc import x, A, B >>> Not(True) False >>> Not(False) True >>> Not(And(True, False)) True >>> Not(Or(True, False)) False >>> Not(And(And(True, x), Or(x, False))) ~x >>> ~x ~x >>> Not(And(Or(A, B), Or(~A, ~B))) ~((A | B) & (~A | ~B)) Notes ===== - The ``~`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise not. In particular, ``~a`` and ``Not(a)`` will be different if ``a`` is an integer. Furthermore, since bools in Python subclass from ``int``, ``~True`` is the same as ``~1`` which is ``-2``, which has a boolean value of True. To avoid this issue, use the SymPy boolean types ``true`` and ``false``. - As of Python 3.12, the bitwise not operator ``~`` used on a Python ``bool`` is deprecated and will emit a warning. >>> from sympy import true >>> ~True # doctest: +SKIP -2 >>> ~true False Tct|ts|dvr|rtStS|jr|j dS|j r |jSy)NTFr)r(rr'r&is_Notr7r"r)r6r s r.evalzNot.evalsM c6 "c]&:5 )T ) ::88A;    ;;  r0cv|jdjjtjS)z Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import Not, Symbol >>> x = Symbol('x') >>> Not(x > 0).as_set() Interval(-oo, 0) r)r7r complementrr}rXs r.rzzNot._eval_as_sets*yy|""$//88r0c t|r|S|jd}|j|j}}|tk(r,t j |Dcgc] }t |c}d|iS|tk(r,tj |Dcgc] }t |c}d|iS|tk(r&|\}}tj |t ||S|tk(r;tj t |t |Dcgc] }t |c}|S|tk(r{g}tdt|dzdD]H} t|| D]7} |D cgc]} | | vr t | n| } } |jt | 9Jtj |d|iS|tk(rM|\}}} tj t |t | t t |t ||Std|zcc}wcc}wcc}wcc} w)NrrKrrtz!Illegal operator %s in expression)rr7rrOrTrrWr\rlrar~rwr rITEr@)r<rKexprrr7r rrMr_rnegrclauser%s r.rpz Not.to_nnfs d Kyy|YY d 3;::D9SC9MHM M 2:;;T :cS :NXN N 7?DAq;;q#a&8;< < : ;;r4y"4.HCs3x.H*I(02 2 3;F1c$ik1- /'a0/CAEFASc!fa7FFFMM"f+./ /;;:: : 3;GAq!;;r!SV}bQQ.@8;T T>> from sympy.logic.boolalg import Xor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Xor(True, False) True >>> Xor(True, True) False >>> Xor(True, False, True, True, False) True >>> Xor(True, False, True, False) False >>> x ^ y x ^ y Notes ===== The ``^`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise xor. In particular, ``a ^ b`` and ``Xor(a, b)`` will be different if ``a`` and ``b`` are integers. >>> Xor(x, y).subs(y, 0) x T)rct}t||g|i|}|jD]}t |t s|dvr |rt }n!t |tr8|jD](}||vr|j|n|j|*i||vr|j||j||Dcgc]1}|jr#||j|jjf3} }d} g} t| D]V\} \}} }t| dzt!| D]}| |dd\}}||k(r| } n || k(snD| j#||fX| r2t |vr|jt n|jt | D]'\}}|j||j|)t!|dk(rt$St!|dk(r|j'Sd|vr$|r"|jdt)t|St+t-||_t/||_|Scc}w)NrFrtrrT)rrr8_argsr(rr&rar7remover r"rr enumerater~rwrr'rxrWtupler frozenset_argset)r6rr7rBr objr rrr$oddrrr%rjr{rjcjrMrs r.r8z Xor.__new__s0goc3D3F399 C#v&#*>C#s#GA()V FMM!$AG c" 3 3!//1;; 3 3433&s^ #MAz1b1q5#c(+ QB8!'C1W   MM1b' " # #'6>FMM$ vzz$7G DAq MM!  MM!   v;! L [A ::<  V^ MM$ sF|$ $gfo.CI#F+CKJ=3s6Ic>tt|jSr4rrrrXs r.r7zXor.args&WT\\*++r0c>g}tdt|jdzdD]\}t|j|D]A}|jDcgc]}||vr t |n|}}|j t |C^tj|d|iScc}w)NrrtrrK) r~rwr7r rWrrTrOr)r<rKr7rrrrs r.rpz Xor.to_nnf+sq#dii.*A. )A#DIIq1 )=AYYGAH#a&!3GG BK( ) ){{D4844HsBc |j}ttt|Dcgc]}t ||jc}Scc}wr4)r7rT_get_odd_parity_termsrw_convert_to_varsSOPr<r7rBrrs r._eval_rewrite_as_OrzXor._eval_rewrite_as_Or3sG II23q6:<(4995<= =<A c |j}ttt|Dcgc]}t ||jc}Scc}wr4)r7rO_get_even_parity_termsrw_convert_to_varsPOSrs r._eval_rewrite_as_AndzXor._eval_rewrite_as_And8sG II4SV<>)DII6>? ?>rc |j|jDcgc]}|jdi|c}}|j}t |t s|St }t|||ddScc}w)Nr7r2)rr7rKrr(ra_simplify_patterns_xorrF)r<rBrrrSs r.rzXor._eval_simplify=svTYYtyyA!-f-A B YY["c"I)+1"h282CTK K BsA5ct|trit|j}|j |jr8t|j|z }|j ||j |Syyr4)r(rarr7r'r r)r<r)rr+r7s r.r,zXor._eval_subsIse c3 #((mG *499~/  tyy$''+ r0r)rrrrr8rrr7rprrrr,rrs@r.rarasJ&N)-.d , ,5= ? K(r0rac eZdZdZedZy)rqa Logical NAND function. It evaluates its arguments in order, giving True immediately if any of them are False, and False if they are all True. Returns True if any of the arguments are False Returns False if all arguments are True Examples ======== >>> from sympy.logic.boolalg import Nand >>> from sympy import symbols >>> x, y = symbols('x y') >>> Nand(False, True) True >>> Nand(True, True) False >>> Nand(x, y) ~(x & y) c$tt|Sr4)rWrOr5s r.rz Nand.evall3:r0Nrrrrrrr2r0r.rqrqTs.r0rqc eZdZdZedZy)rYa* Logical NOR function. It evaluates its arguments in order, giving False immediately if any of them are True, and True if they are all False. Returns False if any argument is True Returns True if all arguments are False Examples ======== >>> from sympy.logic.boolalg import Nor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Nor(True, False) False >>> Nor(True, True) False >>> Nor(False, True) False >>> Nor(False, False) True >>> Nor(x, y) ~(x | y) c$tt|Sr4)rWrTr5s r.rzNor.evals2t9~r0Nrr2r0r.rYrYqs8r0rYc eZdZdZedZy)Xnora  Logical XNOR function. Returns False if an odd number of the arguments are True and the rest are False. Returns True if an even number of the arguments are True and the rest are False. Examples ======== >>> from sympy.logic.boolalg import Xnor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Xnor(True, False) False >>> Xnor(True, True) True >>> Xnor(True, False, True, True, False) False >>> Xnor(True, False, True, False) True c$tt|Sr4)rWrar5s r.rz Xnor.evalrr0Nrr2r0r.rrs2r0rc0eZdZdZedZddZddZy)r\a  Logical implication. A implies B is equivalent to if A then B. Mathematically, it is written as `A \Rightarrow B` and is equivalent to `\neg A \vee B` or ``~A | B``. Accepts two Boolean arguments; A and B. Returns False if A is True and B is False Returns True otherwise. Examples ======== >>> from sympy.logic.boolalg import Implies >>> from sympy import symbols >>> x, y = symbols('x y') >>> Implies(True, False) False >>> Implies(False, False) True >>> Implies(True, True) True >>> Implies(False, True) True >>> x >> y Implies(x, y) >>> y << x Implies(x, y) Notes ===== The ``>>`` and ``<<`` operators are provided as a convenience, but note that their use here is different from their normal use in Python, which is bit shifts. Hence, ``Implies(a, b)`` and ``a >> b`` will return different things if ``a`` and ``b`` are integers. In particular, since Python considers ``True`` and ``False`` to be integers, ``True >> True`` will be the same as ``1 >> 1``, i.e., 0, which has a truth value of False. To avoid this issue, use the SymPy objects ``true`` and ``false``. >>> from sympy import true, false >>> True >> False 1 >>> true >> false False c4 g}|D]B}t|ts|dvr|jt|2|j|D|\}}|dvs|dvrtt||S||k(rtS|jrQ|jrE|j|jk(rtS|jj|jk(r|Sytj|g|S#t$r#t dt |t |fzwxYw)Nrrtz:%d operand(s) used for an Implies (pairs are required): %sr)r(rrboolr@rwstrrTrWr&r"rrrr8)r6r7r#rABs r.rz Implies.evals EG &a(AKNN47+NN1%  & DAq m!3c!fa= !VK __{{akk) yy""akk12==,t, , E+.1$iT-CDE E Es AC++,Dcb|j\}}tjt|||SNr)r7rTrrW)r<rKrrMs r.rpzImplies.to_nnfs(yy1zz#a&!hz77r0cn|j\}}tjt|t |||S)Nr )r7rarr&rO)r<rrrMs r.rzImplies.to_anfs,yy1{{4C1ID{99r0Nr)rrrrrrrprr2r0r.r\r\s&/`--28:r0r\cLeZdZdZfdZeedZddZddZ xZ S)rla Equivalence relation. ``Equivalent(A, B)`` is True iff A and B are both True or both False. Returns True if all of the arguments are logically equivalent. Returns False otherwise. For two arguments, this is equivalent to :py:class:`~.Xnor`. Examples ======== >>> from sympy.logic.boolalg import Equivalent, And >>> from sympy.abc import x >>> Equivalent(False, False, False) True >>> Equivalent(True, False, False) False >>> Equivalent(x, And(x, True)) True cddlm}|Dcgc] }t|}}t|}|D]B}t |t s|dvs|j ||jt|Dg}|D]A}t ||s|j||j|jjfCg} t|D]Z\} \}} } t| dzt|D]6} || dd\}}|| k(r tccS|| k(s#| j||fZ\| D]8\}}|j!||j!||jd:t|dkrt"Sd|vr|j dt%|Sd|vr0|j dt%|Dcgc] }t'|c}St)|}t*|Y||}||_|Scc}wcc}w)NrrerrtrTF)rhrfrrr(rdiscardr rrrrrr~rwr'rr&rOrWrrr8r)r6r7optionsrfr r rr$rrrr%rjr{rrrrMrrrs r.r8zEquivalent.__new__s4)-.# ..T $A!V$](:q! 47# $ BA!Z( Aq{{AII,?,?@A B&s^ MAz1b1q5#c(+ QB8 L1WMM1b'*    DAq MM!  MM!  JJt   v;! K 6> NN4 <  F? NN5 !V4cS45 5&!goc5)  G/>5s G*0G/c>tt|jSr4rrXs r.r7zEquivalent.argsGrr0cJg}t|j|jddD])\}}|jtt ||+|jtt |jd|jdt j |d|iS)NrtrrK)zipr7rrTrWrOr)r<rKr7rrMs r.rpzEquivalent.to_nnfLs 499QR=1 'DAq KK3q61 & ' Bs499R=)499Q<89{{D4844r0c t|j}t|jDcgc]}tt|dc}}t |}t j |||Scc}w)NFr )rOr7rrWr^rar)r<rrr rMs r.rzEquivalent.to_anfSsX O $))D3&S.D E #A &{{1ad{++EsA*r) rrrrr8rrr7rprrrs@r.rlrls4.%R , ,5,r0rlc:eZdZdZdZedZddZdZdZ y) raC If-then-else clause. ``ITE(A, B, C)`` evaluates and returns the result of B if A is true else it returns the result of C. All args must be Booleans. From a logic gate perspective, ITE corresponds to a 2-to-1 multiplexer, where A is the select signal. Examples ======== >>> from sympy.logic.boolalg import ITE, And, Xor, Or >>> from sympy.abc import x, y, z >>> ITE(True, False, True) False >>> ITE(Or(True, False), And(True, True), Xor(True, True)) True >>> ITE(x, y, z) ITE(x, y, z) >>> ITE(True, x, y) x >>> ITE(False, x, y) y >>> ITE(x, y, y) y Trying to use non-Boolean args will generate a TypeError: >>> ITE(True, [], ()) Traceback (most recent call last): ... TypeError: expecting bool, Boolean or ITE, not `[]` chddlm}m}t|dk7r t d|\}}}t |||frt t||f\}}tj||fDcgc]}|jc}} tt|j| z dk(r|} |jtur |j}nu|jtur |j}nV|jturt!|j}n.|jturt!|j}nt}t | |r't!|}nt"j%|||\}}}d} |j'ddr|j)|||} | t"j+||||d } | Scc}w) Nrrzexpecting exactly 3 argsrtrTFr;)rhrrrwr@r(mapr/rrrr7r>r&r?r'rWrrrrr8) r6r7rBrrrrMr%rbin_syms_ars r.r8z ITE.__new__~sp0 t9>78 81a a"b "zAq6*DAq"su{{1v$F!Q%5%5$FGH3qvv;)*a/55D=AUUd]AUUe^AEE AUUe^AEE AAb"%AA%??1aGAq!  ::j$ '!Q"B : ((aA(FB 3%Gs&F/cFddlm}m}|\}}}t|||fr|}t|j vr+|j tur |jn |j }nQt|j vr=|j turt|jnt|j }nd}|t||r t|}|tur|S|tur|S||k(r|S|tur |tur|S|tur|tur t|S|||g|k7r ||||dSy)NrrFr;) rhrrr(r&r7r?r>r'rW)r6r7rrrrMr%rs r.rzITE.evals01a a"b "Bqvv~UUd]AEE!&&"#%%5.CJc!%%j~*R"4F 9H :H 6HDyQ%ZEza4i1v q!9 q!Q/ / r0c|j\}}}tjtt ||t|||Sr)r7rOrrTrW)r<rKrrMr%s r.rpz ITE.to_nnfs6))1a{{2c!fa="Q(X{FFr0c>|jjSr4)rprrXs r.rzzITE._eval_as_sets{{}##%%r0c:ddlm}||d|df|ddfS)NrrrtrT)rr)r<r7rBrs r._eval_rewrite_as_PiecewisezITE._eval_rewrite_as_Piecewises'B$q'47+d1gt_==r0Nr) rrrrr8rrrprzrr2r0r.rrZs2"F$L00<G&>r0rc eZdZdZedZy) Exclusivea True if only one or no argument is true. ``Exclusive(A, B, C)`` is equivalent to ``~(A & B) & ~(A & C) & ~(B & C)``. For two arguments, this is equivalent to :py:class:`~.Xor`. Examples ======== >>> from sympy.logic.boolalg import Exclusive >>> Exclusive(False, False, False) True >>> Exclusive(False, True, False) True >>> Exclusive(False, True, True) False c g}t|dD])\}}|jtt||+t|S)Nr)r rrWrO)r6r7and_argsrrMs r.rzExclusive.evalsA q) ,DAq OOCAq N + ,H~r0Nrr2r0r.rrs&r0rc,tj|S)aReturn a list of the conjuncts in ``expr``. Examples ======== >>> from sympy.logic.boolalg import conjuncts >>> from sympy.abc import A, B >>> conjuncts(A & B) frozenset({A, B}) >>> conjuncts(A | B) frozenset({A | B}) )rO make_argsrs r. conjunctsrs == r0c,tj|S)aReturn a list of the disjuncts in ``expr``. Examples ======== >>> from sympy.logic.boolalg import disjuncts >>> from sympy.abc import A, B >>> disjuncts(A | B) frozenset({A, B}) >>> disjuncts(A & B) frozenset({A & B}) )rTrrs r. disjunctsrs << r0c.t|ttfS)ai Given a sentence ``expr`` consisting of conjunctions and disjunctions of literals, return an equivalent sentence in CNF. Examples ======== >>> from sympy.logic.boolalg import distribute_and_over_or, And, Or, Not >>> from sympy.abc import A, B, C >>> distribute_and_over_or(Or(A, And(Not(B), Not(C)))) (A | ~B) & (A | ~C) ) _distributerOrTrs r.distribute_and_over_orrs c2 ''r0c.t|ttfS)a Given a sentence ``expr`` consisting of conjunctions and disjunctions of literals, return an equivalent sentence in DNF. Note that the output is NOT simplified. Examples ======== >>> from sympy.logic.boolalg import distribute_or_over_and, And, Or, Not >>> from sympy.abc import A, B, C >>> distribute_or_over_and(And(Or(Not(A), B), C)) (B & C) | (C & ~A) )rrTrOrs r.distribute_or_over_andr!s b# ''r0c.t|ttfS)a Given a sentence ``expr`` consisting of conjunction and exclusive disjunctions of literals, return an equivalent exclusive disjunction. Note that the output is NOT simplified. Examples ======== >>> from sympy.logic.boolalg import distribute_xor_over_and, And, Xor, Not >>> from sympy.abc import A, B, C >>> distribute_xor_over_and(And(Xor(Not(A), B), C)) (B & C) ^ (C & ~A) )rrarOrs r.r^r^4s c3' ((r0c@t|d|dr|djD]}t||ds|}n|dS|d|djDcgc] }||us| c}}|dttt|jDcgc]}|d|||d|dfc}ddiSt|d|drF|dttt|djDcgc] }||d|dfc}ddiS|dScc}wcc}wcc}w)zO Distributes ``info[1]`` over ``info[2]`` with respect to ``info[0]``. rrrtrF)r(r7rArr)infor conjrrestr%rs r.rrGsd$q'47#7<< C#tAw'  7NtAwDGLLBqATMBCtAwS+/99"6&'$+471d#3T!Wd1g"F"678LEJL L DGT!W %tAwS+/7<<"9&'$%d1gtAw"7"9:;*$)* * AwC"6"9s DD D+DcVt|}t|r|S|j|S)a\ Converts expr to Algebraic Normal Form (ANF). ANF is a canonical normal form, which means that two equivalent formulas will convert to the same ANF. A logical expression is in ANF if it has the form .. math:: 1 \oplus a \oplus b \oplus ab \oplus abc i.e. it can be: - purely true, - purely false, - conjunction of variables, - exclusive disjunction. The exclusive disjunction can only contain true, variables or conjunction of variables. No negations are permitted. If ``deep`` is ``False``, arguments of the boolean expression are considered variables, i.e. only the top-level expression is converted to ANF. Examples ======== >>> from sympy.logic.boolalg import And, Or, Not, Implies, Equivalent >>> from sympy.logic.boolalg import to_anf >>> from sympy.abc import A, B, C >>> to_anf(Not(A)) A ^ True >>> to_anf(And(Or(A, B), Not(C))) A ^ B ^ (A & B) ^ (A & C) ^ (B & C) ^ (A & B & C) >>> to_anf(Implies(Not(A), Equivalent(B, C)), deep=False) True ^ ~A ^ (~A & (Equivalent(B, C))) r )ris_anfr)rrs r.rr_s+J 4=D d| ;;D; !!r0c@t||r|S|j|S)aS Converts ``expr`` to Negation Normal Form (NNF). A logical expression is in NNF if it contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`, and :py:class:`~.Not` is applied only to literals. If ``simplify`` is ``True``, the result contains no redundant clauses. Examples ======== >>> from sympy.abc import A, B, C, D >>> from sympy.logic.boolalg import Not, Equivalent, to_nnf >>> to_nnf(Not((~A & ~B) | (C & D))) (A | B) & (~C | ~D) >>> to_nnf(Equivalent(A >> B, B >> A)) (A | ~B | (A & ~B)) & (B | ~A | (B & ~A)) )is_nnfrp)rrKs r.rprps"(dH ;;x  r0ct|}t|ts|S|r<|s+tt |dkDrt t dt|dd|St|r|St|}t|}|S)ao Convert a propositional logical sentence ``expr`` to conjunctive normal form: ``((A | ~B | ...) & (B | C | ...) & ...)``. If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest CNF form using the Quine-McCluskey algorithm; this may take a long time. If there are more than 8 variables the ``force`` flag must be set to ``True`` to simplify (default is ``False``). Examples ======== >>> from sympy.logic.boolalg import to_cnf >>> from sympy.abc import A, B, D >>> to_cnf(~(A | B) | D) (D | ~A) & (D | ~B) >>> to_cnf((A | B) & (A | ~A), True) A | B  To simplify a logical expression with more than 8 variables may take a long time and requires the use of `force=True`.cnfTforce) rr(rrw_find_predicatesr@r"ris_cnfeliminate_implicationsr)rrKrress r.to_cnfrs( 4=D dO , -d34q8Z)()* *dE4u==d| !$ 'D  &C Jr0ct|}t|ts|S|r<|s+tt |dkDrt t dt|dd|St|r|St|}t|S)a Convert a propositional logical sentence ``expr`` to disjunctive normal form: ``((A & ~B & ...) | (B & C & ...) | ...)``. If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest DNF form using the Quine-McCluskey algorithm; this may take a long time. If there are more than 8 variables, the ``force`` flag must be set to ``True`` to simplify (default is ``False``). Examples ======== >>> from sympy.logic.boolalg import to_dnf >>> from sympy.abc import A, B, C >>> to_dnf(B & (A | C)) (A & B) | (B & C) >>> to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True) A | C rrdnfTr) rr(rrwrr@r"ris_dnfrr)rrKrs r.to_dnfrs( 4=D dO , -d34q8Z)()* *dE4u==d| !$ 'D !$ ''r0ct|}t|rt|tsyt|tr |j D]}|j ryyt|trb|j D]R}t|tr!|j D]}|j ry4t|rt|tsPyyyy)a Checks if ``expr`` is in Algebraic Normal Form (ANF). A logical expression is in ANF if it has the form .. math:: 1 \oplus a \oplus b \oplus ab \oplus abc i.e. it is purely true, purely false, conjunction of variables or exclusive disjunction. The exclusive disjunction can only contain true, variables or conjunction of variables. No negations are permitted. Examples ======== >>> from sympy.logic.boolalg import And, Not, Xor, true, is_anf >>> from sympy.abc import A, B, C >>> is_anf(true) True >>> is_anf(A) True >>> is_anf(And(A, B, C)) True >>> is_anf(Xor(A, Not(B))) False TF)rrr(rWrOr7rra)rr rs r.rrs8 4=D$ 4 5$99 C==  D# 99 C#s#%A;;$%Cc3'  r0c*t|}t|ry|g}|rw|j}|jtt fvr@|r"|j }|D]}t||vsy|j|j n t|sy|rwy)a Checks if ``expr`` is in Negation Normal Form (NNF). A logical expression is in NNF if it contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`, and :py:class:`~.Not` is applied only to literals. If ``simplified`` is ``True``, checks if result contains no redundant clauses. Examples ======== >>> from sympy.abc import A, B, C >>> from sympy.logic.boolalg import Not, is_nnf >>> is_nnf(A & B | ~C) True >>> is_nnf((A | ~A) & (B | C)) False >>> is_nnf((A | ~A) & (B | C), False) True >>> is_nnf(Not(A & B) | C) False >>> is_nnf((A >> B) & (B >> A)) False TF) rrrxrrOrTr7rWrC)r simplifiedstackr7r s r.rr.s6 4=D$ FE yy{ 99b !yy%C3x4'$% LL #D!  r0c,t|ttS)a( Test whether or not an expression is in conjunctive normal form. Examples ======== >>> from sympy.logic.boolalg import is_cnf >>> from sympy.abc import A, B, C >>> is_cnf(A | B | C) True >>> is_cnf(A & B & C) True >>> is_cnf((A & B) | C) False )_is_formrOrTrs r.rr_s" D#r ""r0c,t|ttS)aM Test whether or not an expression is in disjunctive normal form. Examples ======== >>> from sympy.logic.boolalg import is_dnf >>> from sympy.abc import A, B, C >>> is_dnf(A | B | C) True >>> is_dnf(A & B & C) True >>> is_dnf((A & B) | C) True >>> is_dnf(A & (B | C)) False )rrTrOrs r.rrss& D"c ""r0ct|}t||r|j|n|g}|D]U}t||r8t||r|j|n|g}|D]}t|dusyGt|dusUyy)zE Test whether or not an expression is of the required form. FT)rr(rr)r function1 function2valslitvals2ls r.rrs 4=D(24(C9  t $$D c9 %0:3 0JI'',QTPUE !a=E)  !_ % r0ct|dS)a Change :py:class:`~.Implies` and :py:class:`~.Equivalent` into :py:class:`~.And`, :py:class:`~.Or`, and :py:class:`~.Not`. That is, return an expression that is equivalent to ``expr``, but has only ``&``, ``|``, and ``~`` as logical operators. Examples ======== >>> from sympy.logic.boolalg import Implies, Equivalent, eliminate_implications >>> from sympy.abc import A, B, C >>> eliminate_implications(Implies(A, B)) B | ~A >>> eliminate_implications(Equivalent(A, B)) (A | ~B) & (B | ~A) >>> eliminate_implications(Equivalent(A, B, C)) (A | ~C) & (B | ~A) & (C | ~B) Fr)rprs r.rrs, $ ''r0cddlmttrt j dSdvsts j rytts tfdj Dryy)a{ Returns True if expr is a literal, else False. Examples ======== >>> from sympy import Or, Q >>> from sympy.abc import A, B >>> from sympy.logic.boolalg import is_literal >>> is_literal(A) True >>> is_literal(~A) True >>> is_literal(Q.zero(A)) True >>> is_literal(A + B) True >>> is_literal(Or(A, B)) False r)AppliedPredicaterTc3RK|]}txs |j ywr4)r(r)rirr rs r.rkzis_literal..s,7RBCZ. / <199 <7Rs$'F) rr r(rWrr7rrall)rr s`@r.rrsk,3$$))A,''  *T3C"D  o .37RGKyy7R4R r0c tt|tdt|dz}d}|Dcgc],}tj |Dchc] }||| c}.c}}Scc}wcc}}w)a  Takes clauses in CNF format and puts them into an integer representation. Examples ======== >>> from sympy.logic.boolalg import to_int_repr >>> from sympy.abc import x, y >>> to_int_repr([x | y, y], [x, y]) == [{1, 2}, {2}] True rtcRt|tr||jd S||Sr:)r(rWr7)r rs r. append_symbolz"to_int_repr..append_symbols, c3 CHHQK(( (3< r0)dictrr~rwrTr)clausesrrr%r s r. to_int_reprrsi3waW)9 :;>> from sympy.logic.boolalg import term_to_integer >>> term_to_integer([1, 0, 0]) 4 >>> term_to_integer('100') 4 r)intjoinrArr)terms r.term_to_integerrs*( rwwtCT$Z012A 66r0c #BK|Dcgc] }t|}}t|}t|ts t|syt dt |}|D]<}|j tt||}|rt||f9|>ycc}ww)a Return a generator of all possible configurations of the input variables, and the result of the boolean expression for those values. Parameters ========== expr : Boolean expression variables : list of variables input : bool (default ``True``) Indicates whether to return the input combinations. Examples ======== >>> from sympy.logic.boolalg import truth_table >>> from sympy.abc import x,y >>> table = truth_table(x >> y, [x, y]) >>> for t in table: ... print('{0} -> {1}'.format(*t)) [0, 0] -> True [0, 1] -> True [1, 0] -> False [1, 1] -> True >>> table = truth_table(x | y, [x, y]) >>> list(table) [([0, 0], False), ([0, 1], True), ([1, 0], True), ([1, 1], True)] If ``input`` is ``False``, ``truth_table`` returns only a list of truth values. In this case, the corresponding input values of variables can be deduced from the index of a given output. >>> from sympy.utilities.iterables import ibin >>> vars = [y, x] >>> values = truth_table(x >> y, vars, input=False) >>> values = list(values) >>> values [True, False, True, True] >>> for i, value in enumerate(values): ... print('{0} -> {1}'.format(list(zip( ... vars, ibin(i, len(vars)))), value)) [(y, 0), (x, 0)] -> True [(y, 0), (x, 1)] -> False [(y, 1), (x, 0)] -> True [(y, 1), (x, 1)] -> True Nrrepeat) rr(rrr rwrBrrrA)r variablesinputvtablervalues r. truth_tabler  sh&///I/ 4=D dO ,Z5E F3y> 2E d3y$#789 t*e# #K 0sBBBBcTd}t|D]\}}|||k7s|dk(r|}y|S)zm Checks if a pair of minterms differs by only one bit. If yes, returns index, else returns `-1`. r)r)minterm1minterm2indexrrs r. _check_pairr%QsC E(#1  {  Lr0ct|Dcgc]"\}}|dk7r|dk(r||n t||$}}}t|Scc}}w)zh Converts a term in the expansion of a function from binary to its variable form (for SOP). rrt)rrWrO)mintermrnvaltemps r.rrbsW $G, :3q 1HIaL#il*; ; :D : : :'Act|Dcgc]"\}}|dk7r|dk(r||n t||$}}}t|Scc}}w)zh Converts a term in the expansion of a function from binary to its variable form (for POS). rr)rrWrT)maxtermrr(r)r*s r.rrlsW $G, :3q 1HIaL#il*; ; :D : t9 :r+czt|Dcgc]\}}|dk(s ||}}}|stSt|Scc}}w)z Converts a term in the expansion of a function from binary to its variable form (for ANF). Parameters ========== term : list of 1's and 0's (complementation pattern) variables : list of variables rt)rr&rO)rrr(tr*s r._convert_to_varsANFr0vsA&/t_ ?TQQIaL ?D ?  : @s 77ctd|zDcgc]}t||c}Dcgc]}t|dzdk(s|c}Scc}wcc}w)zu Returns a list of lists, with all possible combinations of n zeros and ones with an odd number of ones. rrtr~r!sumr(rr,s r.rrB -2!Q$K8qQ 8 L!CFQJ!OA LL8 LAA A ctd|zDcgc]}t||c}Dcgc]}t|dzdk(s|c}Scc}wcc}w)zv Returns a list of lists, with all possible combinations of n zeros and ones with an even number of ones. rrr2r4s r.rrr5r6c>|sgSg}ttt|}tt}t |D]+\}}t d|D}||j |-t|d}t|D]^}||D]T} ||dzD]G} t|| || } | dk7sdx|| <|| <|| dd} d| | <| |vs7|j | IV`|r t|}|j|D cgc] } | ||  c} |Scc} w)z Reduces a set of minterms, if possible, to a simplified set of minterms with one less variable in the terms using QM method. c3,K|] }|dk(s dyw)rtNr2)rir/s r.rkz$_simplified_pairs..s-a1f1-s rrtrNr) rAr~rwr rr3rr%_simplified_pairsrC) termssimplified_termstodotermdictr(ronesrrPrr{r$newterms r.r:r:sR   c%j! "D4 HU#!4-d--a !E!H I 9  9! 9Aac] 9#E!HeAh7B;(,,DGd1g#AhqkG%&GEN&66(//8 9 9 9,-=>tE!q}U1XEF Fs D Dc |sgSt|}t|}t|Dcgc]}dg|z }}dg|z}dg|z}t|D]W\}} t|D]D\} } tdt | | Ds#d|| |<||xxdz cc<|| xxdz cc<FYd} | r#d} t|D]} || s || t|D]p}| |k7s || s|| ||ks||tfdt|Ds?d||<d} tD]\}} | s d|||<||xxdzcc<ri}t|D]}||s ||vr||n$t|Dcgc] }||| c}||<t|D]}||k7s ||s||||k\s||vr||n$t|Dcgc] }||| c}||<tfdt|Dshd||<d} tD]&\} } | s || |sd|| |<|| xxdzcc<(| sd}d}t|D]}||}||kDs|}|}|dk7rd|dkDr_t|D]Q\}} ||k7s t||D]5\} } | s || |sd|| |<d} || xxdzcc<||xxdzcc<7S| r#t|Dcgc] }||s ||c}Scc}wcc}wcc}wcc}w) z After the truth table has been sufficiently simplified, use the prime implicant table method to recognize and eliminate redundant pairs, and return the essential arguments. rc3:K|]\}}|dk(xs||k(yw)rNr2)rir/mts r.rkz"_rem_redundancy..s$CB16$Q"W$CsrtTFc34K|]}||k\ywr4r2)rir(rowrow2s r.rkz"_rem_redundancy..sEQtAw#a&0Ec34K|]}||k\ywr4r2)rir(colcol2s r.rkz"_rem_redundancy.. sHQs1va0HrGr)rwr~rr r)l1r;ntermsnl1r( dommatrixcolcountrowcountprimeiprimetermiranythingchangedrowirow2icolcachecolircol2imaxterms bestcolidxrrIrJrErFs @@@@r._rem_redundancyr\s  ZF b'C#(-0Q!S0I0s3wHs6zH"2% $U+ %KE4C#eT2BCC+, % ( A% 1$  %%O &M :D~o"6] :Eu}$Xd^xX]=^(/E%*EE./HUO.2O1:4: #(?@Ie$4V$<$,V$4$9$4 : :  :$#J 9D~8#"4.C7_ H,#+E?DAFv#OAIaL$7#OD.2HUOH%-HH./HUO.2O/89 t#'Ie,?Ie$4U$;$,UOq$8O 99 94HJc  !TNxD/ c3  NN4T? + T "y/Kxxz (""3' (VC ,<= :[!,- i8!89 :dE] +3x4 "$$*FF$577 NN49 %./ /%/( N 9s E Nc|stSttt|}t ||}t |xsg|}|D]}||vst d|zt |||S)a The SOPform function uses simplified_pairs and a redundant group- eliminating algorithm to convert the list of all input combos that generate '1' (the minterms) into the smallest sum-of-products form. The variables must be given as the first argument. Return a logical :py:class:`~.Or` function (i.e., the "sum of products" or "SOP" form) that gives the desired outcome. If there are inputs that can be ignored, pass them as a list, too. The result will be one of the (perhaps many) functions that satisfy the conditions. Examples ======== >>> from sympy.logic import SOPform >>> from sympy import symbols >>> w, x, y, z = symbols('w x y z') >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], ... [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]] >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] >>> SOPform([w, x, y, z], minterms, dontcares) (y & z) | (~w & ~x) The terms can also be represented as integers: >>> minterms = [1, 3, 7, 11, 15] >>> dontcares = [0, 2, 5] >>> SOPform([w, x, y, z], minterms, dontcares) (y & z) | (~w & ~x) They can also be specified using dicts, which does not have to be fully specified: >>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}] >>> SOPform([w, x, y, z], minterms) (x & ~w) | (y & z & ~x) Or a combination: >>> minterms = [4, 7, 11, [1, 1, 1, 1]] >>> dontcares = [{w : 0, x : 0, y: 0}, 5] >>> SOPform([w, x, y, z], minterms, dontcares) (w & y & z) | (~w & ~y) | (x & z & ~w) See also ======== POSform References ========== .. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm .. [2] https://en.wikipedia.org/wiki/Don%27t-care_term #%s in minterms is also in dontcares)r'rrrrgr@ _sop_form)rminterms dontcaresrfs r.SOPformrmE svx  c'9-.I!95H!9?Y?I H =BQFG GH Y) 44r0c t||z}t||}t|Dcgc]}t||c}Scc}wr4)r:r\rTr)rrkrlr essentialrs r.rjrj s> Hy0 1CX.I 9Ea#Ay1E FFEs;c |stSttt|}t ||}t |xsg|}|D]}||vst d|zg}t dt|D](}t|}||vs||vs|j|*t||z}t||}t|Dcgc]}t||c}Scc}w)a The POSform function uses simplified_pairs and a redundant-group eliminating algorithm to convert the list of all input combinations that generate '1' (the minterms) into the smallest product-of-sums form. The variables must be given as the first argument. Return a logical :py:class:`~.And` function (i.e., the "product of sums" or "POS" form) that gives the desired outcome. If there are inputs that can be ignored, pass them as a list, too. The result will be one of the (perhaps many) functions that satisfy the conditions. Examples ======== >>> from sympy.logic import POSform >>> from sympy import symbols >>> w, x, y, z = symbols('w x y z') >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], ... [1, 0, 1, 1], [1, 1, 1, 1]] >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] >>> POSform([w, x, y, z], minterms, dontcares) z & (y | ~w) The terms can also be represented as integers: >>> minterms = [1, 3, 7, 11, 15] >>> dontcares = [0, 2, 5] >>> POSform([w, x, y, z], minterms, dontcares) z & (y | ~w) They can also be specified using dicts, which does not have to be fully specified: >>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}] >>> POSform([w, x, y, z], minterms) (x | y) & (x | z) & (~w | ~x) Or a combination: >>> minterms = [4, 7, 11, [1, 1, 1, 1]] >>> dontcares = [{w : 0, x : 0, y: 0}, 5] >>> POSform([w, x, y, z], minterms, dontcares) (w | x) & (y | ~w) & (z | ~y) See also ======== SOPform References ========== .. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm .. [2] https://en.wikipedia.org/wiki/Don%27t-care_term rirr)r'rrrrgr@r rwrArr:r\rOr) rrkrlrfrZr/rrors r.POSformrq sx  c'9-.I 95H!9?Y?I H =BQFG GHH VC N 3 G X AY$6 OOA  Hy0 1CX.I IFq$Q 2F GGFs=Cc jt|}t|}|d|zk7rtd||fzttt|}t |}g}t td|D]\}}||dk(s|j|!t|Dcgc]}t||c}ddiScc}w)a The ANFform function converts the list of truth values to Algebraic Normal Form (ANF). The variables must be given as the first argument. Return True, False, logical :py:class:`~.And` function (i.e., the "Zhegalkin monomial") or logical :py:class:`~.Xor` function (i.e., the "Zhegalkin polynomial"). When True and False are represented by 1 and 0, respectively, then :py:class:`~.And` is multiplication and :py:class:`~.Xor` is addition. Formally a "Zhegalkin monomial" is the product (logical And) of a finite set of distinct variables, including the empty set whose product is denoted 1 (True). A "Zhegalkin polynomial" is the sum (logical Xor) of a set of Zhegalkin monomials, with the empty set denoted by 0 (False). Parameters ========== variables : list of variables truthvalues : list of 1's and 0's (result column of truth table) Examples ======== >>> from sympy.logic.boolalg import ANFform >>> from sympy.abc import x, y >>> ANFform([x], [1, 0]) x ^ True >>> ANFform([x, y], [0, 1, 1, 1]) x ^ y ^ (x & y) References ========== .. [1] https://en.wikipedia.org/wiki/Zhegalkin_polynomial rz8The number of truth values must be equal to 2^%d, got %drrrtrF) rwr@rrr anf_coeffsrr rrar0) r truthvaluesn_varsn_valuescoeffsr;rr/rs r.ANFformrx sT^F;H1;"%+X$678 8c'9-.I  $F E'&891 !9> LLO EBq$Q 2B "  ""BsB0cdjt|}t|dz }t|d|zk7rtdt|z|Dcgc]}|g}}t|D]]}g}td||z dz zD]@}|j |d|zt t d|d|z|d|zdzzB|}_|dScc}w)a Convert a list of truth values of some boolean expression to the list of coefficients of the polynomial mod 2 (exclusive disjunction) representing the boolean expression in ANF (i.e., the "Zhegalkin polynomial"). There are `2^n` possible Zhegalkin monomials in `n` variables, since each monomial is fully specified by the presence or absence of each variable. We can enumerate all the monomials. For example, boolean function with four variables ``(a, b, c, d)`` can contain up to `2^4 = 16` monomials. The 13-th monomial is the product ``a & b & d``, because 13 in binary is 1, 1, 0, 1. A given monomial's presence or absence in a polynomial corresponds to that monomial's coefficient being 1 or 0 respectively. Examples ======== >>> from sympy.logic.boolalg import anf_coeffs, bool_monomial, Xor >>> from sympy.abc import a, b, c >>> truthvalues = [0, 1, 1, 0, 0, 1, 0, 1] >>> coeffs = anf_coeffs(truthvalues) >>> coeffs [0, 1, 1, 0, 0, 0, 1, 0] >>> polynomial = Xor(*[ ... bool_monomial(k, [a, b, c]) ... for k, coeff in enumerate(coeffs) if coeff == 1 ... ]) >>> polynomial b ^ c ^ (a & b) z{:b}rtrz9The number of truth values must be a power of two, got %dc ||z Sr4r2)rys r.rzanf_coeffs..V s acr0r)rarwr@r~rrAr)rtrr(rrwrtmpr{s r.rsrs% sH  c+&'A A A ;1a4"$' $456 6' 'aqc 'F ' 1XqQqSU|$ IA JJvac{S)6!A#;qs1u FGH I I  !9(s Cct|trt|t|}t t t |}t||S)a Return the k-th minterm. Minterms are numbered by a binary encoding of the complementation pattern of the variables. This convention assigns the value 1 to the direct form and 0 to the complemented form. Parameters ========== k : int or list of 1's and 0's (complementation pattern) variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_minterm >>> from sympy.abc import x, y, z >>> bool_minterm([1, 0, 1], [x, y, z]) x & z & ~y >>> bool_minterm(6, [x, y, z]) x & y & ~z References ========== .. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_minterms )r(rr!rwrrrrrPrs r. bool_mintermr\ <<!S C N #c'9-.I q) ,,r0ct|trt|t|}t t t |}t||S)a Return the k-th maxterm. Each maxterm is assigned an index based on the opposite conventional binary encoding used for minterms. The maxterm convention assigns the value 0 to the direct form and 1 to the complemented form. Parameters ========== k : int or list of 1's and 0's (complementation pattern) variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_maxterm >>> from sympy.abc import x, y, z >>> bool_maxterm([1, 0, 1], [x, y, z]) y | ~x | ~z >>> bool_maxterm(6, [x, y, z]) z | ~x | ~y References ========== .. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_maxterms )r(rr!rwrrrrr~s r. bool_maxtermr rr0ct|trt|t|}t t t |}t||S)aR Return the k-th monomial. Monomials are numbered by a binary encoding of the presence and absences of the variables. This convention assigns the value 1 to the presence of variable and 0 to the absence of variable. Each boolean function can be uniquely represented by a Zhegalkin Polynomial (Algebraic Normal Form). The Zhegalkin Polynomial of the boolean function with `n` variables can contain up to `2^n` monomials. We can enumerate all the monomials. Each monomial is fully specified by the presence or absence of each variable. For example, boolean function with four variables ``(a, b, c, d)`` can contain up to `2^4 = 16` monomials. The 13-th monomial is the product ``a & b & d``, because 13 in binary is 1, 1, 0, 1. Parameters ========== k : int or list of 1's and 0's variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_monomial >>> from sympy.abc import x, y, z >>> bool_monomial([1, 0, 1], [x, y, z]) x & z >>> bool_monomial(6, [x, y, z]) x & y )r(rr!rwrrrr0r~s r. bool_monomialr s=F!S C N #c'9-.I q) ,,r0ct|ts|hStjt t |j S)zHelper to find logical predicates in BooleanFunctions. A logical predicate is defined here as anything within a BooleanFunction that is not a BooleanFunction itself. )r(rrrrrr7rs r.rr s4 dO ,v 35;;-tyy9 ;;r0c|dvr tdt|}|rCd}|dk(r t|}n|dk(r t|}|rt d|j Dr|Sddlm}|rP|j|}dd l m }tt||} |jtt|| }t!|t"s|Si} i} dd lm} |j|}|+t|}|j)|j||r_|j+} | j,r@| }| | |<|| | <| j.}||vrt1|| |<|j3||r_|j| }||j| }t5|}|st7|d kDr|j| S|9t5|}|j)||st7|d kDr t5|}d }t9t;|d d\}}||z}|Dcgc] }|dk(rdnd }}t=|||}|"t=|||}|Dcgc] }||vs| }}ng}t7|dt7|dz zk\}|dk(s||rt?|||j| StA|||j| Scc}wcc}w)ak This function simplifies a boolean function to its simplified version in SOP or POS form. The return type is an :py:class:`~.Or` or :py:class:`~.And` object in SymPy. Parameters ========== expr : Boolean form : string (``'cnf'`` or ``'dnf'``) or ``None`` (default). If ``'cnf'`` or ``'dnf'``, the simplest expression in the corresponding normal form is returned; if ``None``, the answer is returned according to the form with fewest args (in CNF by default). deep : bool (default ``True``) Indicates whether to recursively simplify any non-boolean functions contained within the input. force : bool (default ``False``) As the simplifications require exponential time in the number of variables, there is by default a limit on expressions with 8 variables. When the expression has more than 8 variables only symbolical simplification (controlled by ``deep``) is made. By setting ``force`` to ``True``, this limit is removed. Be aware that this can lead to very long simplification times. dontcare : Boolean Optimize expression under the assumption that inputs where this expression is true are don't care. This is useful in e.g. Piecewise conditions, where later conditions do not need to consider inputs that are converted by previous conditions. For example, if a previous condition is ``And(A, B)``, the simplification of expr can be made with don't cares for ``And(A, B)``. Examples ======== >>> from sympy.logic import simplify_logic >>> from sympy.abc import x, y, z >>> b = (~x & ~y & ~z) | ( ~x & ~y & z) >>> simplify_logic(b) ~x & ~y >>> simplify_logic(x | y, dontcare=y) x References ========== .. [1] https://en.wikipedia.org/wiki/Don%27t-care_term )Nrrzform can be cnf or dnf onlyFrrc32K|]}t|ywr4)r)rirs r.rkz!simplify_logic.. s$&a=$rrer)DummyNrc |dvS)Nrr2rs r.rz simplify_logic..L s a=.@r0Tr4rtr)!r@rrrr r7rhrfrkrrKrrrBrrr(rr%rr`rxr"rrWrrrwr r_get_truthtablerjrq)rformrrdontcareform_okrfrrKrreplundorvarrfnvar dcvariablesr%rr truthtable dctruthtabler/bigs r.rr sl ''677 4=D  5=TlG U]TlG s$$$K0 JJz* 4 #h * +}}T#i"345 dO ,  D D' :&I8$ 34 mmo   ADGDI;;Dy  VT   &  == D$$T*!&I S^a'}}T""&x0 %Y!+(.IH  "$@ NDAqAI()*1a4iQ *A* D!,J&q(A6 !+EAq /DaE E j/aC NQ$67 8C u} J =FFtLL 9j, 7 @ @ FF +Fs"K K K c|jfd|gggDcgc]}|ds ||dz}}|ggk(rgS|Scc}w)zN Return a list of all combinations leading to a True result for ``expr``. c `rj}|Dcgc]1}|dtus|dj|tidg|dzg3}}|j|Dcgc]1}|dtus|dj|tidg|dzg3c}|S|Scc}wcc}w)Nrrt)rxr'rBrCr&)inputsrrtab_get_tt _variabless r.rz _get_truthtable.._get_tt` s  ADJ`qaPQdZ_N_AaDMM1e*-sQqTz:`C` JJd1RSTURV^cRc14y1A31:>d e3<  adsB&%B&B+0%B+rrt)copy)rrconstrPrrrs @@r.rr\ s]!J")4*!6 ?A!A$51Q4< ?C ? rd{  @s A Ac|j}ttt||Dcgc]}dgdzt t gzc}}|j D]}|jr||dxxdz cc< |jr||j ddxxdz cc<Jt|j td|j Df}|j D]f}|jr$||dxxdz cc<||d|xxdz cc<3|jr||j ddxxdz cc<]tdt t}tt|jD]a\}} tt!| djD cgc] \} } | | fz c} } | d<|t| j#|c|Scc}wcc} } w) a Assign a 5-item fingerprint to each symbol in the equation: [ # of times it appeared as a Symbol; # of times it appeared as a Not(symbol); # of times it appeared as a Symbol in an And or Or; # of times it appeared as a Not(Symbol) in an And or Or; a sorted tuple of tuples, (i, j, k), where i is the number of arguments in an And or Or with which it appeared as a Symbol, and j is the number of arguments that were Not(Symbol); k is the number of times that (i, j) was seen. ] Examples ======== >>> from sympy.logic.boolalg import _finger as finger >>> from sympy import And, Or, Not, Xor, to_cnf, symbols >>> from sympy.abc import a, b, x, y >>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y)) >>> dict(finger(eq)) {(0, 0, 1, 0, ((2, 0, 1),)): [x], (0, 0, 1, 0, ((2, 1, 1),)): [a, b], (0, 0, 1, 2, ((2, 0, 1),)): [y]} >>> dict(finger(x & ~y)) {(0, 1, 0, 0, ()): [y], (1, 0, 0, 0, ()): [x]} In the following, the (5, 2, 6) means that there were 6 Or functions in which a symbol appeared as itself amongst 5 arguments in which there were also 2 negated symbols, e.g. ``(a0 | a1 | a2 | ~a3 | ~a4)`` is counted once for a0, a1 and a2. >>> dict(finger(to_cnf(Xor(*symbols('a:5'))))) {(0, 0, 8, 8, ((5, 0, 1), (5, 2, 6), (5, 4, 1))): [a0, a1, a2, a3, a4]} The equation must not have more than one level of nesting: >>> dict(finger(And(Or(x, y), y))) {(0, 0, 1, 0, ((2, 0, 1),)): [x], (1, 0, 1, 0, ((2, 0, 1),)): [y]} >>> dict(finger(And(Or(x, And(a, x)), y))) Traceback (most recent call last): ... NotImplementedError: unexpected level of nesting So y and x have unique fingerprints, but a and b do not. rrtc3<K|]}t|tywr4)r(rW)riais r.rkz_finger.. s FB!4 Fsrrrzunexpected level of nesting)rvrrArr rr7rrrwr3rjriteritemsrsortedr) eqrQfirfrorinvrPrrr{s r._fingerrn s^ A T#aqA1#a%;s#3"44AB CDA WWM ;; aDGqLG XX affQiLOq OAFF S Fqvv FFFAff M<<bE!HMHbE"IaLA%LYYbggajM!$)$-.KLL MM d CQWWY( 1f1R5;;=A41aa1$hABC" E!H Q  J)B$Bs G##G(cVd}t|}t|}|||}|r||fS|S)a Return the simplified version of *bool1*, and the mapping of variables that makes the two expressions *bool1* and *bool2* represent the same logical behaviour for some correspondence between the variables of each. If more than one mappings of this sort exist, one of them is returned. For example, ``And(x, y)`` is logically equivalent to ``And(a, b)`` for the mapping ``{x: a, y: b}`` or ``{x: b, y: a}``. If no such mapping exists, return ``False``. Examples ======== >>> from sympy import SOPform, bool_map, Or, And, Not, Xor >>> from sympy.abc import w, x, y, z, a, b, c, d >>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]]) >>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]]) >>> bool_map(function1, function2) (y & ~z, {y: a, z: b}) The results are not necessarily unique, but they are canonical. Here, ``(w, z)`` could be ``(a, d)`` or ``(d, a)``: >>> eq = Or(And(Not(y), w), And(Not(y), z), And(x, y)) >>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c)) >>> bool_map(eq, eq2) ((x & y) | (w & ~y) | (z & ~y), {w: a, x: b, y: c, z: d}) >>> eq = And(Xor(a, b), c, And(c,d)) >>> bool_map(eq, eq.subs(c, x)) (c & d & (a | b) & (~a | ~b), {a: a, b: b, c: d, d: x}) c|j|jk7ryt|jt|jk7ry|jr||iSt |}t |}t|t|k7ryi}|j D]H}||vryt||t||k7ryt ||D]\}}|||||<J|S)a:Return the mapping that equates variables between two simplified boolean expressions if possible. By "simplified" we mean that a function has been denested and is either an And (or an Or) whose arguments are either symbols (x), negated symbols (Not(x)), or Or (or an And) whose arguments are only symbols or negated symbols. For example, ``And(x, Not(y), Or(w, Not(z)))``. Basic.match is not robust enough (see issue 4835) so this is a workaround that is valid for simplified boolean expressions NF)rrwr7rrr_r)rrf1f2 matchdictrPrrs r.matchzbool_map..match s   )"5"5 5 y~~ #inn"5 5   y) )Y  Y  r7c"g   (A{2a5zSAZ'!"Q%( (1!!uQx !  (  (r0)r)bool1bool2rrrMrLs r.bool_mapr s;H'R uAuA a A!t Hr0c ddlm m}|||}t|j fdd\}}t |dkr|St|dd\}} |D cgc]} | j }} |r(t |dk\rt|||j|||}t|||j|||}|jt|D cgc] } ||  c} |z| z}|Scc} wcc} w) a Replace patterns of Relational Parameters ========== rv : Expr Boolean expression patterns : tuple Tuple of tuples, with (pattern to simplify, simplified pattern) with two terms. measure : function Simplification measure. dominatingvalue : Boolean or ``None`` The dominating value for the function of consideration. For example, for :py:class:`~.And` ``S.false`` is dominating. As soon as one expression is ``S.false`` in :py:class:`~.And`, the whole expression is ``S.false``. replacementvalue : Boolean or ``None``, optional The resulting value for the whole expression if one argument evaluates to ``dominatingvalue``. For example, for :py:class:`~.Nand` ``S.false`` is dominating, but in this case the resulting value is ``S.true``. Default is ``None``. If ``replacementvalue`` is ``None`` and ``dominatingvalue`` is not ``None``, ``replacementvalue = dominatingvalue``. threeterm_patterns : tuple, optional Tuple of tuples, with (pattern to simplify, simplified pattern) with three terms. r)rf _canonicalct|Sr4r2r3s r.rz4_apply_patternbased_simplification..6 s*Q *Cr0Tr4rtc<td|jD S)Nc38K|]}|jduyw)FN)is_real)rirs r.rkzG_apply_patternbased_simplification....: s#2K6734))u2D2Ks)rlrv)rs r.rz4_apply_patternbased_simplification..: s%c2K;<>>2K/K+Kr0r) rhrfrr r7rwr,_apply_patternbased_threeterm_simplificationr*_apply_patternbased_twoterm_simplificationr) rrSr7dominatingvaluereplacementvaluer<rrGrH nonRealRelrrfs @r.rFrF sN=O$?*rww C"$KC 3x1} 3!K"&(OC!$ $11;; $C $c#h!m:3.,g7 5S(GG_.> IC 73<8aJqM8&' )B I %9s C!C&cddlm}m}ddlm}m} m} d} | r#t|dk\rd} |D cgc]} t| || fr | jn|  }} tt|}|D cgc]} t| | r| fn | | jf!} } g}tt| dD]\\}}\}}|D]\}}g}t||D]8\}}t||}|j!|}|s&|j#||f:|sR|D]\}}|j%|}||k(r |gcccSt|t&r6|j)||rI|||j*||z }|dkDsm|j#|||g|ff|rt-|dd}|dd }|\}}|j/t|D]}||=||t1|k7rC|j2|k(r#|j*D]} |j#| n|j#|d} | rt|dk\r|Scc} wcc} w) z- Apply pattern-based two-term simplification.rMinMax)ruGt _InequalityTrFc |dSr:r2pairs r.rz<_apply_patternbased_twoterm_simplification..{ DGr0rereversert)(sympy.functions.elementary.miscellaneousrrrhrurrrwr(reversedrArr rr rrrrBrrir7rsortrWr)!rGrSrrrr7rrrurrchangedrrtmpresultsrpir{pjpatternsimprp1p2oldexprtmpresnp costsaving replacementidxnewrelr$rs! r.rrL sn B99G c#h!mEHIZB84qzz!;II73< RUVQA{3!QZZHVV".y"B K Wagq"!) K %b"o6FB#BmG$]]73F FG#45 6+. K!]]620%5#55)"c2266#s;K*1w||1D)EPR )SJ)A~ ' aVRL/I J K K K2 W/CTSG"!*Q-K%KC HHJ!# J &&C4H*H;;$&#[[& 1 &JJv&Gq c#h!mr JmJWs #H=*$Ic ddlm}m}ddlm}m} m} d} | r+t|dk\rd} |D cgc]} t| || fr | jn|  }} tt|}g} |D cgc]} t| | r| fn | | jf!}} tt|dD]\\}}\}}\}}|D]\}}g}t|||D]:\}}}t|||}|j!|}|s(|j#||f<|sU|D]\}}|j%|}||k(r |gcccSt|t&r6|j)||rI|||j*||z }|dkDsm| j#||||g|ff| rt-| dd} | dd }|\} }!| j/t| D]}"||"=||!t1|k7rC|!j2|k(r#|!j*D]}#|j#|#n|j#|!d} | rt|dk\r|Scc} wcc} w) z/ Apply pattern-based three-term simplification.rr)rtLtrTrFc |dSr:r2rs r.rz>_apply_patternbased_threeterm_simplification.. rr0rrt)rrrrhrtrrrwr(rrArr rr rrrrBrrir7rrrWr)$rGrSrrrr7rrrtrrrrrrrrr{rrPpkrrrrrp3rrrrrrrr$rs$ r.rr s~ B99G c#h!mEHIZB84qzz!;II73< RUVQA{3!QZZHVV+7 $+K N 'Wagq"w2!) N ")"b""56JBB#BB/G$]]73F FG#45 6+. N!]]620%5#55)"c2266#s;K*1w||1D)EPR )SJ)A~ ' aAYO/L M N N N2 W/CTSG"!*Q-K%KC HHJ!# J &&C4H*H;;$&#[[& 1 &JJv&Gq c#h!mr JmJ Ws #I,$I c ddlm}ddlm}m}m}m}m}m}ddl m }ddl m }m } |d} |d} |d} t|| | || | tft|| | || | tft|| | || | || | ft|| | || | || | ft|| | || | || | ft|| | || | || | ft|| | || | || | ft|| | || | t!|| t"j$|| t"j$ft|| | || | || | | | ft|| | || | t'| | kD|| | || | ft|| | || | || | | | ft|| | || | || || | ft|| | || | t'| | k|| | || | ft|| | || | || || | ft|| | || | t'|| | || | t'| | ktt!|| | || | ft|| | || | t'|| | || | t'| | ktt!|| | || | ft|| | || | t'| | ktt!|| | || | ft|| | || | t'| | ktt!|| | || | ft|| | || | t'| | ktt!|| | || | ft|| | || | t'| | ktt!|| | || | ft|| | || | t'|| | || | tft|| | || | t'| dkD||| | tft|| | || | t'| dk\||| | tff} | S) z Two-term patterns for And.rWildrrrurrtrAbsrrrMr%) sympy.corerrhrrrurrtr$sympy.functions.elementary.complexesrrrrrr'rOrrr)rrrrurrtrrrrrrMr% _matchers_ands r.rDrD s <<8A S A S A S ABq!HbAh/7Bq!HbAh/7Bq!HbAh/Aq:Bq!HbAh/Aq:Bq!HbAh/Aq:Bq!HbAh/Aq:Bq!HbAh/Aq:Bq!HbQBi0#bAFFmR166]2STBq!HbAh/As1ay1ABBq!HbAh/QUBq!HbAh1OPBq!HbAh/As1ay1ABBq!HbAh/As1ay1ABBq!HbAh/QUBq!HbAh1OPBq!HbAh/As1ay1ABBq!HbAh/R1Xr!QxQQRUTY[^_abcef_giklmopiq[rIs1tuBq!HbAh/R1Xr!QxQQRUTY[^_abcef_giklmopiq[rIs1tuBq!HbAh/QUE3r!QxQSTUWXQYCZ1[\Bq!HbAh/QUE3r!QxQSTUWXQYCZ1[\Bq!HbAh/Q!VUC1aRTUVXYRZD[1\]Bq!HbAh/Q!VUC1aRTUVXYRZD[1\]Bq!HbAh/R1Xr!Qx1OPBq!Hb!Qi0#a!eRA]E2RSBq!Hb!Qi0#a1fbQmU2ST? MB r0cBddlm}ddlm}m}m}|d}|d}|d}t |||||||||tft |||||||||tft |||||||||tft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ft |||||||||t||||||ff}|S)z Three-term patterns for And.rr)rrurrrMr%) rrrhrrurrr'rO)rrrurrrMr%rs r.rErE sd 00 S A S A S ABq!HbAh1a95ABq!HbAh1a95ABq!HbAh1a95ABq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RSBq!HbAh1a93r!QxAq;RS3M6 r0c ~ ddlm}ddlm}m}m}m}m}m}ddl m }ddl m }m } |d} |d} |d} t|| | || | tft|| | || | tft|| | || | || | ft|| | || | || | ft|| | || | || | ft|| | || | || | ft|| | || | || | ft|| | || | t!|| | t|| | ft|| | || | t!|| | || | tft|| | || | || || | ft|| | || | t!| | kD|| | || | ft|| | || | || || | ft|| | || | || | | | ft|| | || | t!| | k\|| | || | ft|| | || | || | | | ft|| | || | t!| | k\tt#|| | || | ft|| | || | t!| | k\tt#|| | || | ft|| | || | t!| | kDtt#|| | || | ft|| | || | t!| | kDtt#|| | || | ft|| | || | t!| | k\tt#|| | || | ft|| | || | t!| | k\tt#|| | || | ft|| | || | t!| dk\||| | tft|| | || | t!| dkD||| | tff} | S) z Two-term patterns for Or.rrrrrrrMr%)rrrhrrrurrtrrrrrrrr&rrT)rrrrurrtrrrrrrMr% _matchers_ors r.rwrw1 s\ <<8A S A S A S A2a8R1X.52a8R1X.5 2a8R1X.1a92a8R1X.1a92a8R1X.1a92a8R1X.1a92a8R1X.1a92a8R1X.Bq!HdBq!H0MN2a8R1X.Bq!HbAh0MN2a8R1X.1c!Qi0@A2a8R1X.AE2a8R1X0NO2a8R1X.1c!Qi0@A2a8R1X.1c!Qi0@A2a8R1X.AFBq!HbAh0OP2a8R1X.1c!Qi0@A2a8R1X.AFD"R1XrRSUVxBX0YZ2a8R1X.AFD"R1XrRSUVxBX0YZ2a8R1X.AE4Bq!HbQRTUhAW0XY2a8R1X.AE4Bq!HbQRTUhAW0XY2a8R1X.AFD"R1XrRSUVxBX0YZ2a8R1X.AFD"R1XrRSUVxBX0YZ2a8RA2Y/Q!VRA]D1QR2a8RA2Y/QUBs1vqM41PQE#LH r0czddlm}m}ddlm}ddlm}m}m}m }m }m }|d} |d} |d} t|| | || | || | ft|| | || | || | ft|| | || | || | ft|| | || | || | ft|| | || | || | ft|| | || | || | ft|| | || | t|| || | || || | ft|| | || | t| | kDt|| | || | t|| | || | ft|| | || | t|| || | || || | ft|| | || | t|| || | || || | ft|| | || | t| | kt|| | || | t|| | || | ft|| | || | t|| || | || || | ff } | S)z Two-term patterns for Xor.rrrrrrMr%)rrrrrrhrrrurrtrrrOr) rrrrrrurrtrrrMr% _matchers_xors r.rrf sB<< S A S A S ABq!HbAh/Aq:Bq!HbAh/Aq:Bq!HbAh/Aq:Bq!HbAh/Aq:Bq!HbAh/Aq:Bq!HbAh/Aq: Bq!HbAh/"QAq *Bq#a),<=?Bq!HbAh/!a%R1Xr!Qx!8bAh1a134Bq!HbAh/"QAq *Bq#a),<=?Bq!HbAh/"QAq *Bq#a),<=?Bq!HbAh/!a%R1Xr!Qx!8bAh1a134Bq!HbAh/"QAq *Bq#a),<=?7M< r0cJddlm}ddlm}m}t |t s|S|j||r|S|}|j}t|dk7r|S|j}|d|fdj|d\}}|s|S|stSg} |D]\} } } } | tjur:| tjurt }n|j#|| dk(r|| k}n|| k}n|j#|| dk(} |j#|| dk(}| r'|r%| j$r|| k\}nat'| |k|| k}nN| rt'| |k|| k}n9|r%| j$r|| kD}n%t'| |k|| k}nt'| |k|| k}| j)| t+| S) zKreturn a simplified version of univariate boolean expression, else ``expr``rrrrtFr;T) err_on_Eq)rrrhrrr(rrkrvrwrx _intervalsr'rNegativeInfinityInfinityr&r? is_infiniterOrrT)rrrrr%rrokrr7rrM_incl_aincl_bs r.rr s>, dO ,  zz"b  A >>D 4yA~  A q!fu jdj+ B   D 1a "" "AJJ66!Q<4'aAQAffQld*FffQld*F&==aAAFAF+AQA&==QAAE16*AAq1u% A56 t9r0ct|ts tdt|tr2t |j t d|j DzSy)a Return the total number of inputs for the logic gates realizing the Boolean expression. Returns ======= int Number of gate inputs Note ==== Not all Boolean functions count as gate here, only those that are considered to be standard gates. These are: :py:class:`~.And`, :py:class:`~.Or`, :py:class:`~.Xor`, :py:class:`~.Not`, and :py:class:`~.ITE` (multiplexer). :py:class:`~.Nand`, :py:class:`~.Nor`, and :py:class:`~.Xnor` will be evaluated to ``Not(And())`` etc. Examples ======== >>> from sympy.logic import And, Or, Nand, Not, gateinputcount >>> from sympy.abc import x, y, z >>> expr = And(x, y) >>> gateinputcount(expr) 2 >>> gateinputcount(Or(expr, z)) 4 Note that ``Nand`` is automatically evaluated to ``Not(And())`` so >>> gateinputcount(Nand(x, y, z)) 4 >>> gateinputcount(Not(And(x, y, z))) 4 Although this can be avoided by using ``evaluate=False`` >>> gateinputcount(Nand(x, y, z, evaluate=False)) 3 Also note that a comparison will count as a Boolean variable: >>> gateinputcount(And(x > z, y >= 2)) 2 As will a symbol: >>> gateinputcount(x) 0 zExpression must be Booleanc32K|]}t|ywr4)gateinputcount)rirs r.rkz!gateinputcount..s#I!N1$5#Irr)r(r*r+ BooleanGatesrwr7r3rs r.rr sJj dG $455$ %499~#Ityy#I III r0r)FFr4)NTFN)NN)}r __future__rtypingrrrcollections.abcrr collectionsr itertoolsr r r r sympy.core.addrsympy.core.basicrsympy.core.cachersympy.core.containersrsympy.core.decoratorsrrsympy.core.functionrrsympy.core.kindrrsympy.core.numbersrsympy.core.operationsrsympy.core.singletonrrsympy.core.sortingrsympy.core.sympifyrrrsympy.utilities.iterablesr r!sympy.utilities.miscr"r/r*rrrr&r'rrrOrTrWrarqrYrr\rlrrrrrrr^rrrprrrrrrrrrrrinteger_to_termr r%rrr0rrr:r\rgrmrjrqrxrsrrrrrrrrrFrrrDrErwrrrrr2r0r.rs#//-#@@"$'E73%+-&BB0+&@R^e^^B0'0fq+qhG;)GT}  7Vk7Vrf)_fRp3Op3fq:/q:hE(/E(P?:/D?>Q:oQ:hQ,Q,hr>/r>j>""("(&)&0)"X!2'T%(P5p.b#(#,((2D67.AH"(MM(Vc6L4H5VG NHb;"|4n!-H!-H&-R <@GF$DNR n9=:>?DAHAH . .b ' 'T 1 1h * *Z/hRdCdC8 9 r0