def test_Equivalent(): assert Equivalent(A, B) == Equivalent(B, A) == Equivalent(A, B, A) assert Equivalent() is True assert Equivalent(A, A) == Equivalent(A) is True assert Equivalent(True, True) == Equivalent(False, False) is True assert Equivalent(True, False) == Equivalent(False, True) is False assert Equivalent(A, True) == A assert Equivalent(A, False) == Not(A) assert Equivalent(A, B, True) == A & B assert Equivalent(A, B, False) == ~A & ~B
def test_is_nnf(): from sympy.abc import A, B assert is_nnf(true) is True assert is_nnf(A) is True assert is_nnf(~A) is True assert is_nnf(A & B) is True assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), False) is True assert is_nnf((A | B) & (~A | ~B)) is True assert is_nnf(Not(Or(A, B))) is False assert is_nnf(A ^ B) is False assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), True) is False
def test_bool_map(): """ Test working of bool_map function. """ minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]] assert bool_map(Not(Not(a)), a) == (a, {a: a}) assert bool_map(SOPform([w, x, y, z], minterms), POSform([w, x, y, z], minterms)) == \ (And(Or(Not(w), y), Or(Not(x), y), z), {x: x, w: w, z: z, y: y}) assert bool_map(SOPform([x, z, y], [[1, 0, 1]]), SOPform([a, b, c], [[1, 0, 1]])) != False function1 = SOPform([x, z, y], [[1, 0, 1], [0, 0, 1]]) function2 = SOPform([a, b, c], [[1, 0, 1], [1, 0, 0]]) assert bool_map(function1, function2) == \ (function1, {y: a, z: b}) assert bool_map(Xor(x, y), ~Xor(x, y)) == False assert bool_map(And(x, y), Or(x, y)) is None assert bool_map(And(x, y), And(x, y, z)) is None
def test_is_literal(): assert is_literal(True) is True assert is_literal(False) is True assert is_literal(A) is True assert is_literal(~A) is True assert is_literal(Or(A, B)) is False assert is_literal(Q.zero(A)) is True assert is_literal(Not(Q.zero(A))) is True assert is_literal(Or(A, B)) is False assert is_literal(And(Q.zero(A), Q.zero(B))) is False assert is_literal(x < 3) assert not is_literal(x + y < 3)
def test_Not(): assert Not(Equality(x, y)) == Unequality(x, y) assert Not(Unequality(x, y)) == Equality(x, y) assert Not(StrictGreaterThan(x, y)) == LessThan(x, y) assert Not(StrictLessThan(x, y)) == GreaterThan(x, y) assert Not(GreaterThan(x, y)) == StrictLessThan(x, y) assert Not(LessThan(x, y)) == StrictGreaterThan(x, y)
def test_simplification(): """ Test working of simplification methods. """ set1 = [[0, 0, 1], [0, 1, 1], [1, 0, 0], [1, 1, 0]] set2 = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1]] from sympy.abc import w, x, y, z assert SOPform('xyz', set1) == Or(And(Not(x), z), And(Not(z), x)) assert Not(SOPform('xyz', set2)) == And(Or(Not(x), Not(z)), Or(x, z)) assert POSform('xyz', set1 + set2) is True assert SOPform('xyz', set1 + set2) is True assert SOPform([Dummy(), Dummy(), Dummy()], set1 + set2) is True 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]] assert ( SOPform('wxyz', minterms, dontcares) == Or(And(Not(w), z), And(y, z))) assert POSform('wxyz', minterms, dontcares) == And(Or(Not(w), y), z) # test simplification ans = And(A, Or(B, C)) assert simplify_logic('A & (B | C)') == ans assert simplify_logic('(A & B) | (A & C)') == ans # check input ans = SOPform('xy', [[1, 0]]) assert SOPform([x, y], [[1, 0]]) == ans assert POSform(['x', 'y'], [[1, 0]]) == ans raises(ValueError, lambda: SOPform('x', [[1]], [[1]])) assert SOPform('x', [[1]], [[0]]) is True assert SOPform('x', [[0]], [[1]]) is True assert SOPform('x', [], []) is False raises(ValueError, lambda: POSform('x', [[1]], [[1]])) assert POSform('x', [[1]], [[0]]) is True assert POSform('x', [[0]], [[1]]) is True assert POSform('x', [], []) is False #check working of simplify assert simplify('(A & B) | (A & C)') == sympify('And(A, Or(B, C))') assert simplify(And(x, Not(x))) == False assert simplify(Or(x, Not(x))) == True
def test_to_nnf(): assert to_nnf(true) is true assert to_nnf(false) is false assert to_nnf(A) == A assert to_nnf(A | ~A | B) is true assert to_nnf(A & ~A & B) is false assert to_nnf(A >> B) == ~A | B assert to_nnf(Equivalent(A, B, C)) == (~A | B) & (~B | C) & (~C | A) assert to_nnf(A ^ B ^ C) == \ (A | B | C) & (~A | ~B | C) & (A | ~B | ~C) & (~A | B | ~C) assert to_nnf(ITE(A, B, C)) == (~A | B) & (A | C) assert to_nnf(Not(A | B | C)) == ~A & ~B & ~C assert to_nnf(Not(A & B & C)) == ~A | ~B | ~C assert to_nnf(Not(A >> B)) == A & ~B assert to_nnf(Not(Equivalent(A, B, C))) == And(Or(A, B, C), Or(~A, ~B, ~C)) assert to_nnf(Not(A ^ B ^ C)) == \ (~A | B | C) & (A | ~B | C) & (A | B | ~C) & (~A | ~B | ~C) assert to_nnf(Not(ITE(A, B, C))) == (~A | ~B) & (A | ~C) assert to_nnf((A >> B) ^ (B >> A)) == (A & ~B) | (~A & B) assert to_nnf((A >> B) ^ (B >> A), False) == \ (~A | ~B | A | B) & ((A & ~B) | (~A & B)) assert ITE(A, 1, 0).to_nnf() == A assert ITE(A, 0, 1).to_nnf() == ~A # although ITE can hold non-Boolean, it will complain if # an attempt is made to convert the ITE to Boolean nnf raises(TypeError, lambda: ITE(A < 1, [1], B).to_nnf())
def test_Not(): raises(TypeError, lambda: Not(True, False)) assert Not(True) is false assert Not(False) is true assert Not(0) is true assert Not(1) is false assert Not(2) is false
def test_Equivalent(self): assert Equivalent(true, false) is false assert Equivalent(0, D) is Not(D) assert Equivalent(Equivalent(A, B), C) is not Equivalent(Equivalent(C, Equivalent(A, B))) assert Equivalent(B < 1, B >= 1) is false assert Equivalent(C < 1, C >= 1, 0) is false assert Equivalent(D < 1, D >= 1, 1) is false assert Equivalent(E < 1, S(1) > E) is Equivalent(1, 1) assert Equivalent(Equality(C, D), Equality(D, C)) is true #to_nnf in Equivalent (could be in Equivalent) assert to_nnf(Equivalent(D, B, C)) == (~D | B) & (~B | C) & (~C | D)
def test_to_cnf(): assert to_cnf(~(B | C)) == And(Not(B), Not(C)) assert to_cnf((A & B) | C) == And(Or(A, C), Or(B, C)) assert to_cnf(A >> B) == (~A) | B assert to_cnf(A >> (B & C)) == (~A | B) & (~A | C) assert to_cnf(Equivalent(A, B)) == And(Or(A, Not(B)), Or(B, Not(A))) assert to_cnf(Equivalent(A, B & C)) == (~A | B) & (~A | C) & (~B | ~C | A) assert to_cnf(Equivalent(A, B | C)) == \ And(Or(Not(B), A), Or(Not(C), A), Or(B, C, Not(A)))
def entailment_1(a, b, decomposition, constraints): a = prepare_for_SAT(a) b = prepare_for_SAT(b) affirm = And(a, b) deny = And(a, Not(b)) affirmZ = get_f_Z(affirm, decomposition, constraints) denyZ = get_f_Z(deny, decomposition, constraints) #print("Affirm Z: %s" % (affirmZ)) #print("Deny Z: %s" % (denyZ)) if affirmZ < denyZ: return True else: return False
def convert_implications(s): if s.is_symbol: return s if s.func == Implies: a, b = s.args s = Or(b, Not(a)) args = [] for arg in s.args: args.append(convert_implications(arg)) return s.func(*args)
def piecewise_fold(expr): """ Takes an expression containing a piecewise function and returns the expression in piecewise form. Examples ======== >>> from sympy import Piecewise, piecewise_fold, sympify as S >>> from sympy.abc import x >>> p = Piecewise((x, x < 1), (1, S(1) <= x)) >>> piecewise_fold(x*p) Piecewise((x**2, x < 1), (x, 1 <= x)) See Also ======== Piecewise """ if not isinstance(expr, Basic) or not expr.has(Piecewise): return expr new_args = map(piecewise_fold, expr.args) if expr.func is ExprCondPair: return ExprCondPair(*new_args) piecewise_args = [] for n, arg in enumerate(new_args): if isinstance(arg, Piecewise): piecewise_args.append(n) if len(piecewise_args) > 0: n = piecewise_args[0] new_args = [(expr.func(*(new_args[:n] + [e] + new_args[n + 1:])), c) for e, c in new_args[n].args] if isinstance(expr, Boolean): # If expr is Boolean, we must return some kind of PiecewiseBoolean. # This is constructed by means of Or, And and Not. # piecewise_fold(0 < Piecewise( (sin(x), x<0), (cos(x), True))) # can't return Piecewise((0 < sin(x), x < 0), (0 < cos(x), True)) # but instead Or(And(x < 0, 0 < sin(x)), And(0 < cos(x), Not(x<0))) other = True rtn = False for e, c in new_args: rtn = Or(rtn, And(other, c, e)) other = And(other, Not(c)) if len(piecewise_args) > 1: return piecewise_fold(rtn) return rtn if len(piecewise_args) > 1: return piecewise_fold(Piecewise(*new_args)) return Piecewise(*new_args) else: return expr.func(*new_args)
def test_Not(): raises(TypeError, lambda: Not(True, False)) assert Not(True) is False assert Not(False) is True assert Not(0) is True assert Not(1) is False assert Not(2).func is Not
def test_Boolean_Class(self): #__and__(self, other) assert true.__and__(true) is not false #__or__(self, other) assert true.__or__(false) is not false #__invert__(self) assert true.__invert__() is false #__lshift__(self, other) assert true.__lshift__(false) is true #__rshift__(self) assert true.__rshift__(true) is true #rrshift = lshift assert true.__rrshift__(false) is true.__lshift__(false) #rlshift = rshift assert true.__rlshift__(false) is true.__rshift__(false) #__xor__(self, other) assert true.__xor__(true) is false #rxor = xor assert true.__rxor__(true) is true.__xor__(true) # equals(self, other) assert Not(And(True, False, False)).equals(And(Not(True), Not(False), Not(False))) is False # to_nnf(self, simplify=True) assert Not(True).to_nnf() is false # as_set() assert Equality(1, 0).as_set() is Equality(1, 0).as_set() assert And(-2 < 1, 1 < 2).as_set() is And(-2 < 1, 1 < 2).as_set()
def __new__(cls, expr, predicate=None, value=True): from sympy import Q if predicate is None: predicate = Q.is_true elif not isinstance(predicate, Predicate): key = str(predicate) try: predicate = getattr(Q, key) except AttributeError: predicate = Predicate(key) if value: return Boolean.__new__(cls, expr, predicate) else: return Not(Boolean.__new__(cls, expr, predicate))
def per_fnd(q : IntEnum, rep : np.array): conjs = [] for c in rep: conj = [] n, p = c if p == n == Z: continue for i in range(0, len(q)): j = I << i if p & j: conj.append(Symbol(q(i).name)) if n & j: conj.append(Not(Symbol(q(i).name))) conjs.append(And(*conj)) return Or(*conjs)
def find_pure_symbol(symbols, unknown_clauses): """Find a symbol and its value if it appears only as a positive literal (or only as a negative) in clauses. >>> from sympy import symbols >>> A, B, C = symbols('ABC') >>> find_pure_symbol([A, B, C], [A|~B,~B|~C,C|A]) (A, True) """ for sym in symbols: found_pos, found_neg = False, False for c in unknown_clauses: if not found_pos and sym in disjuncts(c): found_pos = True if not found_neg and Not(sym) in disjuncts(c): found_neg = True if found_pos != found_neg: return sym, found_pos return None, None
def test_relational_logic_symbols(): # See issue 6204 assert (x < y) & (z < t) == And(x < y, z < t) assert (x < y) | (z < t) == Or(x < y, z < t) assert ~(x < y) == Not(x < y) assert (x < y) >> (z < t) == Implies(x < y, z < t) assert (x < y) << (z < t) == Implies(z < t, x < y) assert (x < y) ^ (z < t) == Xor(x < y, z < t) assert isinstance((x < y) & (z < t), And) assert isinstance((x < y) | (z < t), Or) assert isinstance(~(x < y), GreaterThan) assert isinstance((x < y) >> (z < t), Implies) assert isinstance((x < y) << (z < t), Implies) assert isinstance((x < y) ^ (z < t), (Or, Xor))
def test_numpy_logical_ops(): if not numpy: skip("numpy not installed.") and_func = lambdify((x, y), And(x, y), modules="numpy") and_func_3 = lambdify((x, y, z), And(x, y, z), modules="numpy") or_func = lambdify((x, y), Or(x, y), modules="numpy") or_func_3 = lambdify((x, y, z), Or(x, y, z), modules="numpy") not_func = lambdify((x), Not(x), modules="numpy") arr1 = numpy.array([True, True]) arr2 = numpy.array([False, True]) arr3 = numpy.array([True, False]) numpy.testing.assert_array_equal(and_func(arr1, arr2), numpy.array([False, True])) numpy.testing.assert_array_equal(and_func_3(arr1, arr2, arr3), numpy.array([False, False])) numpy.testing.assert_array_equal(or_func(arr1, arr2), numpy.array([True, True])) numpy.testing.assert_array_equal(or_func_3(arr1, arr2, arr3), numpy.array([True, True])) numpy.testing.assert_array_equal(not_func(arr2), numpy.array([True, False]))
def convert_icondition_2_conjunctive_formula(icondition, ne_symbols): ic_symbols = list() for ne in ne_symbols: if ne in icondition.ne_iset_ids: ic_symbols.append(ne_symbols[ne]) else: ic_symbols.append(Not(ne_symbols[ne])) if len(ic_symbols) == 0: return true formula = ic_symbols[0] for i in range(1, len(ic_symbols)): formula = And(formula, ic_symbols[i]) return formula
def _get_formula(truth_assignments, propositions): dnfs = [] props = dict([(p, symbols(p)) for p in propositions]) for truth_assignment in truth_assignments: dnf = [] for p in props: if p in truth_assignment: dnf.append(props[p]) else: dnf.append(Not(props[p])) dnfs.append(And(*dnf)) formula = Or(*dnfs) formula = simplify_logic(formula, form='dnf') formula = str(formula).replace('(', '').replace(')', '').replace( '~', '!').replace(' ', '') return formula
def dpll(clauses, symbols, model): """ Compute satisfiability in a partial model. Clauses is an array of conjuncts. >>> from sympy.abc import A, B, D >>> from sympy.logic.algorithms.dpll import dpll >>> dpll([A, B, D], [A, B], {D: False}) False """ # compute DP kernel P, value = find_unit_clause(clauses, model) while P: model.update({P: value}) symbols.remove(P) if not value: P = ~P clauses = unit_propagate(clauses, P) P, value = find_unit_clause(clauses, model) P, value = find_pure_symbol(symbols, clauses) while P: model.update({P: value}) symbols.remove(P) if not value: P = ~P clauses = unit_propagate(clauses, P) P, value = find_pure_symbol(symbols, clauses) # end DP kernel unknown_clauses = [] for c in clauses: val = pl_true(c, model) if val is False: return False if val is not True: unknown_clauses.append(c) if not unknown_clauses: return model if not clauses: return model P = symbols.pop() model_copy = model.copy() model.update({P: True}) model_copy.update({P: False}) symbols_copy = symbols[:] return (dpll(unit_propagate(unknown_clauses, P), symbols, model) or dpll( unit_propagate(unknown_clauses, Not(P)), symbols_copy, model_copy))
def test_operators(): # Mostly test __and__, __rand__, and so on assert True & A == A & True == A assert False & A == A & False == False assert A & B == And(A, B) assert True | A == A | True == True assert False | A == A | False == A assert A | B == Or(A, B) assert ~A == Not(A) assert True >> A == A << True == A assert False >> A == A << False == True assert A >> True == True << A == True assert A >> False == False << A == ~A assert A >> B == B << A == Implies(A, B) assert True ^ A == A ^ True == ~A assert False ^ A == A ^ False == A assert A ^ B == Xor(A, B)
def union(i, j, m, N): o = False a = True t = True kb_o, kb_a = check(i, j, m, N) for k in kb_o: x = symbols(k) o = Or(o, x) for k in kb_a: x = symbols(k) a = And(a, Not(x)) if (len(kb_o) == 0): t = And(True, a) else: t = And(o, a) #print(satisfiable(t)) return t
def assign_extensions(formula, worlds, propositions): extension = [] if str(formula).isspace() or len(str(formula)) == 0 or str( formula ) == "TRUE": #if the formula is empty it will be treated as a toutology #print("Check Empty\n") for w in worlds.values(): extension.append(w.state) return extension if str(formula) == "FALSE": return extension else: props_in_formula = set() #store propositions found in the formula for char in str(formula): add = Symbol(char) props_in_formula.add(add) props_not_in_form = propositions.difference( props_in_formula ) #Determine which propositions are missing from the rule's body supplement = Symbol('') #print("formula: %s " % (formula)) form_cnf = to_cnf(formula) for p in props_not_in_form: supplement = Or( p, Not(p)) #Loop aguments (P | ~P) for each P not found in body form_cnf = And(form_cnf, supplement) #print("__form_cnf: %s \n" % (form_cnf)) form_SAT = satisfiable( form_cnf, all_models=True ) #The sympy SAT solver is applied to the augmented formula form_SAT_list = list( form_SAT ) #the ouput of satisfiable() is an itterator object so we turn it into a list if (len(form_SAT_list) == 1 and form_SAT_list[0] == False): #check to handle inconsistencies extension = [] return extension else: for state in form_SAT_list: #We now turn each state in which the body is true into a dictionary so that new = {} #they may be directly compared with each world state for key, value in state.items(): new[key] = value if new not in extension: extension.append(new) return extension
def test_ITE(): A, B, C = symbols('A:C') assert ITE(True, False, True) is false assert ITE(True, True, False) is true assert ITE(False, True, False) is false assert ITE(False, False, True) is true assert isinstance(ITE(A, B, C), ITE) A = True assert ITE(A, B, C) == B A = False assert ITE(A, B, C) == C B = True assert ITE(And(A, B), B, C) == C assert ITE(Or(A, False), And(B, True), False) is false assert ITE(x, A, B) == Not(x) assert ITE(x, B, A) == x assert ITE(1, x, y) == x assert ITE(0, x, y) == y raises(TypeError, lambda: ITE(2, x, y)) raises(TypeError, lambda: ITE(1, [], y)) raises(TypeError, lambda: ITE(1, (), y)) raises(TypeError, lambda: ITE(1, y, [])) assert ITE(1, 1, 1) is S.true assert isinstance(ITE(1, 1, 1, evaluate=False), ITE) raises(TypeError, lambda: ITE(x > 1, y, x)) assert ITE(Eq(x, True), y, x) == ITE(x, y, x) assert ITE(Eq(x, False), y, x) == ITE(~x, y, x) assert ITE(Ne(x, True), y, x) == ITE(~x, y, x) assert ITE(Ne(x, False), y, x) == ITE(x, y, x) assert ITE(Eq(S. true, x), y, x) == ITE(x, y, x) assert ITE(Eq(S.false, x), y, x) == ITE(~x, y, x) assert ITE(Ne(S.true, x), y, x) == ITE(~x, y, x) assert ITE(Ne(S.false, x), y, x) == ITE(x, y, x) # 0 and 1 in the context are not treated as True/False # so the equality must always be False since dissimilar # objects cannot be equal assert ITE(Eq(x, 0), y, x) == x assert ITE(Eq(x, 1), y, x) == x assert ITE(Ne(x, 0), y, x) == y assert ITE(Ne(x, 1), y, x) == y assert ITE(Eq(x, 0), y, z).subs(x, 0) == y assert ITE(Eq(x, 0), y, z).subs(x, 1) == z raises(ValueError, lambda: ITE(x > 1, y, x, z))
def inclusion(subtask_lib, subtask_new): """ whether subtask_lib is included in subtask_new :param subtask_lib: :param subtask_new: :return: """ # if Equivalent(subtask_lib[0].label, subtask_new[0].label): # print(subtask_lib[0].label, subtask_new[0].label) # A included in B <=> does no exist a truth assignment such that (A & not B) is true if not satisfiable(And(subtask_lib[0].label, Not(subtask_new[0].label))): if subtask_lib[0].x == subtask_new[0].x and subtask_lib[1].x == subtask_new[1].x: return 'forward' elif subtask_lib[0].x == subtask_new[1].x and subtask_lib[1].x == subtask_new[0].x: return 'backward' return ''
def test_ITE(): A, B, C = map(Boolean, symbols('A,B,C')) assert ITE(True, False, True) is false assert ITE(True, True, False) is true assert ITE(False, True, False) is false assert ITE(False, False, True) is true assert isinstance(ITE(A, B, C), ITE) A = True assert ITE(A, B, C) == B A = False assert ITE(A, B, C) == C B = True assert ITE(And(A, B), B, C) == C assert ITE(Or(A, False), And(B, True), False) is false x = symbols('x') assert ITE(x, A, B) == Not(x) assert ITE(x, B, A) == x
def find_pure_symbol(symbols, unknown_clauses): """ Find a symbol and its value if it appears only as a positive literal (or only as a negative) in clauses. >>> from sympy import symbols >>> from sympy.abc import A, B, D >>> from sympy.logic.algorithms.dpll import find_pure_symbol >>> find_pure_symbol([A, B, D], [A|~B,~B|~D,D|A]) (A, True) """ for sym in symbols: found_pos, found_neg = False, False for c in unknown_clauses: if not found_pos and sym in disjuncts(c): found_pos = True if not found_neg and Not(sym) in disjuncts(c): found_neg = True if found_pos != found_neg: return sym, found_pos return None, None