def _recursive_simplify(expr): """Simplify the expression as much as possible based on domain knowledge.""" input_expr = expr # Simplify even further, based on domain knowledge: # windowses = ('WIN32', 'WINRT') apples = ("MACOS", "UIKIT", "IOS", "TVOS", "WATCHOS") bsds = ("FREEBSD", "OPENBSD", "NETBSD") androids = ("ANDROID", ) unixes = ( "APPLE", *apples, "BSD", *bsds, "LINUX", *androids, "HAIKU", "INTEGRITY", "VXWORKS", "QNX", "WASM", ) unix_expr = simplify_logic("UNIX") win_expr = simplify_logic("WIN32") false_expr = simplify_logic("false") true_expr = simplify_logic("true") expr = expr.subs(Not(unix_expr), win_expr) # NOT UNIX -> WIN32 expr = expr.subs(Not(win_expr), unix_expr) # NOT WIN32 -> UNIX # UNIX [OR foo ]OR WIN32 -> ON [OR foo] expr = _simplify_expressions(expr, Or, (unix_expr, win_expr), true_expr) # UNIX [AND foo ]AND WIN32 -> OFF [AND foo] expr = _simplify_expressions(expr, And, (unix_expr, win_expr), false_expr) expr = _simplify_flavors_in_condition("WIN32", ("WINRT", ), expr) expr = _simplify_flavors_in_condition("APPLE", apples, expr) expr = _simplify_flavors_in_condition("BSD", bsds, expr) expr = _simplify_flavors_in_condition("UNIX", unixes, expr) expr = _simplify_flavors_in_condition("ANDROID", (), expr) # Simplify families of OSes against other families: expr = _simplify_os_families(expr, ("WIN32", "WINRT"), unixes) expr = _simplify_os_families(expr, androids, unixes) expr = _simplify_os_families(expr, ("BSD", *bsds), unixes) for family in ("HAIKU", "QNX", "INTEGRITY", "LINUX", "VXWORKS"): expr = _simplify_os_families(expr, (family, ), unixes) # Now simplify further: expr = simplify_logic(expr) while expr != input_expr: input_expr = expr expr = _recursive_simplify(expr) return expr
def _simplify_os_families(expr, family_members, other_family_members): for family in family_members: for other in other_family_members: if other in family_members: continue # skip those in the sub-family f_expr = simplify_logic(family) o_expr = simplify_logic(other) expr = _simplify_expressions(expr, And, (f_expr, Not(o_expr)), f_expr) expr = _simplify_expressions(expr, And, (Not(f_expr), o_expr), o_expr) expr = _simplify_expressions(expr, And, (f_expr, o_expr), simplify_logic("false")) return expr
def missingness_bf_to_factor(bf, bf_var): # This is the error that should be raised when a user attempts to use functionality # that has not yet been implemented. if bf.complement: return Not(Missing(bf_var)) else: return Missing(bf_var)
def test_ContinuousMarkovChain(): T1 = Matrix([[S(-2), S(2), S.Zero], [S.Zero, S.NegativeOne, S.One], [Rational(3, 2), Rational(3, 2), S(-3)]]) C1 = ContinuousMarkovChain('C', [0, 1, 2], T1) assert C1.limiting_distribution() == ImmutableMatrix([[Rational(3, 19), Rational(12, 19), Rational(4, 19)]]) T2 = Matrix([[-S.One, S.One, S.Zero], [S.One, -S.One, S.Zero], [S.Zero, S.One, -S.One]]) C2 = ContinuousMarkovChain('C', [0, 1, 2], T2) A, t = C2.generator_matrix, symbols('t', positive=True) assert C2.transition_probabilities(A)(t) == Matrix([[S.Half + exp(-2*t)/2, S.Half - exp(-2*t)/2, 0], [S.Half - exp(-2*t)/2, S.Half + exp(-2*t)/2, 0], [S.Half - exp(-t) + exp(-2*t)/2, S.Half - exp(-2*t)/2, exp(-t)]]) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert P(Eq(C2(1), 1), Eq(C2(0), 1), evaluate=False) == Probability(Eq(C2(1), 1), Eq(C2(0), 1)) assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2)/2 + S.Half assert P(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1), Eq(P(Eq(C2(1), 0)), S.Half)) == (Rational(1, 4) - exp(-2)/4)*(exp(-2)/2 + S.Half) assert P(Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) | (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)), Eq(P(Eq(C2(1), 0)), Rational(1, 4)) & Eq(P(Eq(C2(1), 1)), Rational(1, 4))) is S.One assert E(C2(Rational(3, 2)), Eq(C2(0), 2)) == -exp(-3)/2 + 2*exp(Rational(-3, 2)) + S.Half assert variance(C2(Rational(3, 2)), Eq(C2(0), 1)) == ((S.Half - exp(-3)/2)**2*(exp(-3)/2 + S.Half) + (Rational(-1, 2) - exp(-3)/2)**2*(S.Half - exp(-3)/2)) raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S.Half))) assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)), S.Half)) == Probability(Eq(C2(1), 0)) TS1 = MatrixSymbol('G', 3, 3) CS1 = ContinuousMarkovChain('C', [0, 1, 2], TS1) A = CS1.generator_matrix assert CS1.transition_probabilities(A)(t) == exp(t*A) C3 = ContinuousMarkovChain('C', [Symbol('0'), Symbol('1'), Symbol('2')], T2) assert P(Eq(C3(1), 1), Eq(C3(0), 1)) == exp(-2)/2 + S.Half assert P(Eq(C3(1), Symbol('1')), Eq(C3(0), Symbol('1'))) == exp(-2)/2 + S.Half
def reaction_to_gene_deletions(reaction_set, rules): rule_set = [rules[r_id] for r_id in reaction_set] merged_rule = to_dnf(Not(Or(*rule_set))) gene_sets = [] if type(merged_rule) is Or: for sub_expr in merged_rule.args: gene_set = [] if type(sub_expr) is And: gene_set = [str(not_gene.args[0]) if type(not_gene) is Not else 'error' for not_gene in sub_expr.args] else: gene_set = [str(sub_expr.args[0]) if type(sub_expr) is Not else 'error'] gene_set = tuple(sorted(set(gene_set))) gene_sets.append(gene_set) elif type(merged_rule) is And: gene_set = [str(not_gene.args[0]) if type(not_gene) is Not else 'error' for not_gene in merged_rule.args] gene_set = tuple(sorted(set(gene_set))) gene_sets.append(gene_set) else: gene_set = [str(merged_rule.args[0]) if type(merged_rule) is Not else 'error'] gene_set = tuple(sorted(set(gene_set))) gene_sets.append(gene_set) return gene_sets
def builtin_function(expr, args=None): """Returns a builtin-function call applied to given arguments.""" if isinstance(expr, Application): name = str(type(expr).__name__) elif isinstance(expr, str): name = expr else: raise TypeError('expr must be of type str or Function') dic = builtin_functions_dict if name in dic.keys(): return dic[name](*args) if name == 'Not': return Not(*args) if name == 'map': func = Function(str(expr.args[0].name)) args = [func] + list(args[1:]) return PythonMap(*args) if name == 'lambdify': return lambdify(expr, args) return None
def test_GammaProcess_numeric(): t, d, x, y = symbols('t d x y', positive=True) X = GammaProcess("X", 1, 2) assert X.state_space == Interval(0, oo) assert X.index_set == Interval(0, oo) assert X.lamda == 1 assert X.gamma == 2 raises(ValueError, lambda: GammaProcess("X", -1, 2)) raises(ValueError, lambda: GammaProcess("X", 0, -2)) raises(ValueError, lambda: GammaProcess("X", -1, -2)) # all are independent because of non-overlapping intervals assert P((X(t) > 4) & (X(d) > 3) & (X(x) > 2) & (X(y) > 1), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))).simplify() == \ 120*exp(-10) # Check working with Not and Or assert P( Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & Contains(d, Interval.Lopen( 7, 8))).simplify() == -4 * exp(-3) + 472 * exp(-8) / 3 + 1 assert P((X(t) > 2) | (X(t) < 4), Contains(t, Interval.Ropen(1, 4))).simplify() == \ -643*exp(-4)/15 + 109*exp(-2)/15 + 1 assert E(X(t)) == 2 * t # E(X(t)) == gamma*t/l assert E(X(2) + x * E(X(5))) == 10 * x + 4
def builtin_function(expr, args=None): """Returns a builtin-function call applied to given arguments.""" if not (isinstance(expr, Application) or isinstance(expr, str)): raise TypeError('Expecting a string or a Function class') if isinstance(expr, Application): name = str(type(expr).__name__) elif isinstance(expr, str): name = expr else: raise TypeError('expr must be of type str or Function') dic = builtin_functions_dict if name in dic.keys() : return dic[name](*args) elif name == 'array': return Array(*args) elif name in ['complex']: if len(args)==1: args = [args[0],Float(0)] return Complex(args[0],args[1]) elif name == 'Not': return Not(*args) elif name == 'map': func = Function(str(expr.args[0].name)) args = [func]+list(args[1:]) return Map(*args) elif name == 'lambdify': return lambdify(expr, args) return None
def test_ContinuousMarkovChain(): T1 = Matrix([[S(-2), S(2), S(0)], [S(0), S(-1), S(1)], [S(3)/2, S(3)/2, S(-3)]]) C1 = ContinuousMarkovChain('C', [0, 1, 2], T1) assert C1.limiting_distribution() == ImmutableMatrix([[S(3)/19, S(12)/19, S(4)/19]]) T2 = Matrix([[-S(1), S(1), S(0)], [S(1), -S(1), S(0)], [S(0), S(1), -S(1)]]) C2 = ContinuousMarkovChain('C', [0, 1, 2], T2) A, t = C2.generator_matrix, symbols('t', positive=True) assert C2.transition_probabilities(A)(t) == Matrix([[S(1)/2 + exp(-2*t)/2, S(1)/2 - exp(-2*t)/2, 0], [S(1)/2 - exp(-2*t)/2, S(1)/2 + exp(-2*t)/2, 0], [S(1)/2 - exp(-t) + exp(-2*t)/2, S(1)/2 - exp(-2*t)/2, exp(-t)]]) assert P(Eq(C2(1), 1), Eq(C2(0), 1), evaluate=False) == Probability(Eq(C2(1), 1)) assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2)/2 + S(1)/2 assert P(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1), Eq(P(Eq(C2(1), 0)), S(1)/2)) == (S(1)/4 - exp(-2)/4)*(exp(-2)/2 + S(1)/2) assert P(Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) | (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)), Eq(P(Eq(C2(1), 0)), S(1)/4) & Eq(P(Eq(C2(1), 1)), S(1)/4)) == S(1) assert E(C2(S(3)/2), Eq(C2(0), 2)) == -exp(-3)/2 + 2*exp(-S(3)/2) + S(1)/2 assert variance(C2(S(3)/2), Eq(C2(0), 1)) == ((S(1)/2 - exp(-3)/2)**2*(exp(-3)/2 + S(1)/2) + (-S(1)/2 - exp(-3)/2)**2*(S(1)/2 - exp(-3)/2)) raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S(1)/2))) assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)), S(1)/2)) == Probability(Eq(C2(1), 0)) TS1 = MatrixSymbol('G', 3, 3) CS1 = ContinuousMarkovChain('C', [0, 1, 2], TS1) A = CS1.generator_matrix assert CS1.transition_probabilities(A)(t) == exp(t*A)
def test_tensorflow_logical_operations(): if not tensorflow: skip("tensorflow not installed.") expr = Not(And(Or(x, y), y)) func = lambdify([x, y], expr, modules="tensorflow") with tensorflow.compat.v1.Session() as s: assert func(False, True).eval(session=s) == False
def test_WienerProcess(): X = WienerProcess("X") assert X.state_space == S.Reals assert X.index_set == Interval(0, oo) t, d, x, y = symbols('t d x y', positive=True) assert isinstance(X(t), RandomIndexedSymbol) assert X.distribution(t) == NormalDistribution(0, sqrt(t)) raises(ValueError, lambda: PoissonProcess("X", -1)) raises(NotImplementedError, lambda: X[t]) raises(IndexError, lambda: X(-2)) assert X.joint_distribution(X(2), X(3)) == JointDistributionHandmade( Lambda((X(2), X(3)), sqrt(6) * exp(-X(2)**2 / 4) * exp(-X(3)**2 / 6) / (12 * pi))) assert X.joint_distribution(4, 6) == JointDistributionHandmade( Lambda((X(4), X(6)), sqrt(6) * exp(-X(4)**2 / 8) * exp(-X(6)**2 / 12) / (24 * pi))) assert P(X(t) < 3).simplify() == erf(3 * sqrt(2) / (2 * sqrt(t))) / 2 + S(1) / 2 assert P(X(t) > 2, Contains(t, Interval.Lopen(3, 7))).simplify() == S(1)/2 -\ erf(sqrt(2)/2)/2 # Equivalent to P(X(1)>1)**4 assert P((X(t) > 4) & (X(d) > 3) & (X(x) > 2) & (X(y) > 1), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))).simplify() ==\ (1 - erf(sqrt(2)/2))*(1 - erf(sqrt(2)))*(1 - erf(3*sqrt(2)/2))*(1 - erf(2*sqrt(2)))/16 # Contains an overlapping interval so, return Probability assert P((X(t) < 2) & (X(d) > 3), Contains(t, Interval.Lopen(0, 2)) & Contains(d, Interval.Ropen(2, 4))) == Probability( (X(d) > 3) & (X(t) < 2), Contains(d, Interval.Ropen(2, 4)) & Contains(t, Interval.Lopen(0, 2))) assert str(P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & Contains(d, Interval.Lopen(7, 8))).simplify()) == \ '-(1 - erf(3*sqrt(2)/2))*(2 - erfc(5/2))/4 + 1' # Distribution has mean 0 at each timestamp assert E(X(t)) == 0 assert E( x * (X(t) + X(d)) * (X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Ropen(1, 2))) == Expectation( x * (X(d) + X(t)) * (X(d)**2 + X(t)**2), Contains(d, Interval.Ropen(1, 2)) & Contains(t, Interval.Lopen(0, 1))) assert E(X(t) + x * E(X(3))) == 0 #test issue 20078 assert (2 * X(t) + 3 * X(t)).simplify() == 5 * X(t) assert (2 * X(t) - 3 * X(t)).simplify() == -X(t) assert (2 * (0.25 * X(t))).simplify() == 0.5 * X(t) assert (2 * X(t) * 0.25 * X(t)).simplify() == 0.5 * X(t)**2 assert (X(t)**2 + X(t)**3).simplify() == (X(t) + 1) * X(t)**2
def test_tensorflow_logical_operations(): if not tensorflow: skip("tensorflow not installed.") expr = Not(And(Or(x, y), y)) func = lambdify([x, y], expr, modules="tensorflow") a = tensorflow.constant(False) b = tensorflow.constant(True) s = tensorflow.Session() assert func(a, b).eval(session=s) == 0
def test_issue_12587(): # sort holes into intervals p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True)) assert p.integrate((x, -5, 5)) == 23 p = Piecewise((1, x > 1), (2, x < y), (3, True)) lim = x, -3, 3 ans = p.integrate(lim) for i in range(-1, 3): assert ans.subs(y, i) == p.subs(y, i).integrate(lim)
def test_piecewise_fold_piecewise_in_cond(): p1 = Piecewise((cos(x), x < 0), (0, True)) p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True)) p3 = piecewise_fold(p2) assert (p2.subs(x, -pi / 2) == 0.0) assert (p2.subs(x, 1) == 0.0) assert (p2.subs(x, -pi / 4) == 1.0) p4 = Piecewise((0, Eq(p1, 0)), (1, True)) assert (piecewise_fold(p4) == Piecewise( (0, Or(And(Eq(cos(x), 0), x < 0), Not(x < 0))), (1, True))) r1 = 1 < Piecewise((1, x < 1), (3, True)) assert (piecewise_fold(r1) == Not(x < 1)) p5 = Piecewise((1, x < 0), (3, True)) p6 = Piecewise((1, x < 1), (3, True)) p7 = piecewise_fold(Piecewise((1, p5 < p6), (0, True))) assert (Piecewise((1, And(Not(x < 1), x < 0)), (0, True)))
def test_overloading(): """Test that |, & are overloaded as expected""" A, B, C = map(Boolean, symbols('ABC')) assert A & B == And(A, B) assert A | B == Or(A, B) assert (A & B) | C == Or(And(A, B), C) assert A >> B == Implies(A, B) assert A << B == Implies(B, A) assert ~A == Not(A)
def init(): # FIXME: Are (+-)oo correctly handled? Expr.__add__ = \ lambda s, e: Expr(apply_and_simplify(s.expr, e.expr, operator.add)) Expr.__sub__ = \ lambda s, e: Expr(apply_and_simplify(s.expr, e.expr, operator.sub)) Expr.__mul__ = \ lambda s, e: Expr(apply_and_simplify(s.expr, e.expr, operator.mul, \ invert_on_negative=True)) Expr.__div__ = \ lambda s, e: Expr(apply_and_simplify(s.expr, e.expr, operator.div, \ invert_on_negative=True)) Expr.__pow__ = lambda s, e: Expr(s.expr ** e.expr) Expr.__neg__ = lambda s: Expr(-s.expr) Expr.__eq__ = lambda s, e: Expr(Eq(s.expr, e.expr)) Expr.__ne__ = lambda s, e: Expr(Ne(s.expr, e.expr)) Expr.__lt__ = lambda s, e: Expr(Lt(s.expr, e.expr)) Expr.__le__ = lambda s, e: Expr(Le(s.expr, e.expr)) Expr.__gt__ = lambda s, e: Expr(Gt(s.expr, e.expr)) Expr.__ge__ = lambda s, e: Expr(Ge(s.expr, e.expr)) Expr.__and__ = lambda s, e: Expr(And(s.expr, e.expr)) Expr.__or__ = lambda s, e: Expr(Or(s.expr, e.expr)) Expr.__invert__ = lambda s: Expr(Not(s.expr)) Expr.is_eq = lambda s, e: s.expr == e.expr Expr.is_ne = lambda s, e: s.expr != e.expr Expr.is_empty = lambda s: s.is_eq(Expr.empty) Expr.is_inf = lambda s: s.expr == S.Infinity or s.expr == -S.Infinity Expr.is_plus_inf = lambda s: s.expr == S.Infinity Expr.is_minus_inf = lambda s: s.expr == -S.Infinity Expr.is_constant = lambda s: isinstance(s.expr, Integer) Expr.is_integer = lambda s: isinstance(s.expr, Integer) Expr.is_rational = lambda s: isinstance(s.expr, Rational) Expr.is_symbol = lambda s: isinstance(s.expr, Symbol) Expr.is_min = lambda s: isinstance(s.expr, Min) Expr.is_max = lambda s: isinstance(s.expr, Max) Expr.is_add = lambda s: isinstance(s.expr, Add) Expr.is_mul = lambda s: isinstance(s.expr, Mul) Expr.is_pow = lambda s: isinstance(s.expr, Pow) Expr.get_integer = lambda s: s.expr.p Expr.get_numer = lambda s: s.expr.p Expr.get_denom = lambda s: s.expr.q Expr.get_name = lambda s: s.expr.name Expr.compare = lambda s, e: s.compare(e) # Empty. When min/max is invalid. Expr.empty = Expr("EMPTY")
def test_numpy_logical_ops(): if not numpy: skip("numpy not installed.") and_func = lambdify((x, y), And(x, y), modules="numpy") or_func = lambdify((x, y), Or(x, y), modules="numpy") not_func = lambdify((x), Not(x), modules="numpy") arr1 = numpy.array([True, True]) arr2 = numpy.array([False, True]) numpy.testing.assert_array_equal(and_func(arr1, arr2), numpy.array([False, True])) numpy.testing.assert_array_equal(or_func(arr1, arr2), numpy.array([True, True])) numpy.testing.assert_array_equal(not_func(arr2), numpy.array([True, False]))
def _simplify_flavors_in_condition(base: str, flavors, expr): """Simplify conditions based on the knowledge of which flavors belong to which OS.""" base_expr = simplify_logic(base) false_expr = simplify_logic("false") for flavor in flavors: flavor_expr = simplify_logic(flavor) expr = _simplify_expressions(expr, And, (base_expr, flavor_expr), flavor_expr) expr = _simplify_expressions(expr, Or, (base_expr, flavor_expr), base_expr) expr = _simplify_expressions(expr, And, (Not(base_expr), flavor_expr), false_expr) return expr
def test_Equivalent(): A, B, C = map(Boolean, symbols('ABC')) assert Equivalent(A, B) == Equivalent(B, A) == Equivalent(A, B, A) assert Equivalent() == True assert Equivalent(A, A) == Equivalent(A) == True assert Equivalent(True, True) == Equivalent(False, False) == True assert Equivalent(True, False) == Equivalent(False, True) == 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 complete_assumptions(formula): if isinstance(formula, And): return And(*map(CAD.complete_assumptions, formula.args)) elif isinstance(formula, Or): return Or(*map(CAD.complete_assumptions, formula.args)) elif isinstance(formula, Not): return Not(*map(CAD.complete_assumptions, formula.args)) elif type(formula) in CAD.complete_methods: method = CAD.complete_methods.get(type(formula)) return And(formula, method(*formula.args)) return formula
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_ter2symb(): ap = symbols("a b c") tern_0 = "X" actual = ter2symb(None, tern_0) expected = And() assert expected == actual tern_1 = "0X" actual = ter2symb(ap, tern_1) expected = And(Not(Symbol("a"))) assert expected == actual tern_2 = "10" actual = ter2symb(ap, tern_2) expected = And(Symbol("a"), Not(Symbol("b"))) assert expected == actual tern_3 = "0X1" actual = ter2symb(ap, tern_3) expected = And(Not(Symbol("a")), Symbol("c")) assert expected == actual ap = symbols("a b c d e f g h i") tern_4 = "0X110XX01" actual = ter2symb(ap, tern_4) expected = And( Not(Symbol("a")), Symbol("c"), Symbol("d"), Not(Symbol("e")), Not(Symbol("h")), Symbol("i"), ) assert expected == actual
def test_to_cnf(): A, B, C = map(Boolean, symbols('ABC')) 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 __init__(self, prodder): # Atomic-ize any single-thread Prodders in the parallel tree condition = CondEq(Ompizer.lang['thread-num'], 0) # Prod within a while loop until all communications have completed # In other words, the thread delegated to prodding is entrapped for as long # as it's required prod_until = Not(DefFunction(prodder.name, [i.name for i in prodder.arguments])) then_body = List(header=c.Comment('Entrap thread until comms have completed'), body=While(prod_until)) Conditional.__init__(self, condition, then_body) Prodder.__init__(self, prodder.name, prodder.arguments, periodic=prodder.periodic)
def test_ContinuousMarkovChain(): T1 = Matrix([ [S(-2), S(2), S.Zero], [S.Zero, S.NegativeOne, S.One], [Rational(3, 2), Rational(3, 2), S(-3)], ]) C1 = ContinuousMarkovChain("C", [0, 1, 2], T1) assert C1.limiting_distribution() == ImmutableMatrix( [[Rational(3, 19), Rational(12, 19), Rational(4, 19)]]) T2 = Matrix([[-S.One, S.One, S.Zero], [S.One, -S.One, S.Zero], [S.Zero, S.One, -S.One]]) C2 = ContinuousMarkovChain("C", [0, 1, 2], T2) A, t = C2.generator_matrix, symbols("t", positive=True) assert C2.transition_probabilities(A)(t) == Matrix([ [S.Half + exp(-2 * t) / 2, S.Half - exp(-2 * t) / 2, 0], [S.Half - exp(-2 * t) / 2, S.Half + exp(-2 * t) / 2, 0], [ S.Half - exp(-t) + exp(-2 * t) / 2, S.Half - exp(-2 * t) / 2, exp(-t) ], ]) assert P(Eq(C2(1), 1), Eq(C2(0), 1), evaluate=False) == Probability(Eq(C2(1), 1)) assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2) / 2 + S.Half assert P( Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1), Eq(P(Eq(C2(1), 0)), S.Half)) == (Rational(1, 4) - exp(-2) / 4) * (exp(-2) / 2 + S.Half) assert (P( Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) | (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)), Eq(P(Eq(C2(1), 0)), Rational(1, 4)) & Eq(P(Eq(C2(1), 1)), Rational(1, 4)), ) is S.One) assert (E(C2(Rational(3, 2)), Eq(C2(0), 2)) == -exp(-3) / 2 + 2 * exp(Rational(-3, 2)) + S.Half) assert variance(C2(Rational(3, 2)), Eq( C2(0), 1)) == ((S.Half - exp(-3) / 2)**2 * (exp(-3) / 2 + S.Half) + (Rational(-1, 2) - exp(-3) / 2)**2 * (S.Half - exp(-3) / 2)) raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S.Half))) assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)), S.Half)) == Probability(Eq(C2(1), 0)) TS1 = MatrixSymbol("G", 3, 3) CS1 = ContinuousMarkovChain("C", [0, 1, 2], TS1) A = CS1.generator_matrix assert CS1.transition_probabilities(A)(t) == exp(t * A)
def ter2symb(ap, ternary): """Translate ternary output to symbolic.""" expr = And() i = 0 for value in ternary: if value == "1": expr = And(expr, ap[i] if isinstance(ap, tuple) else ap) elif value == "0": assert value == "0" expr = And(expr, Not(ap[i] if isinstance(ap, tuple) else ap)) else: assert value == "X", "[ERROR]: the guard is not X" i += 1 return expr
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 is_complete(self) -> bool: """ Check whether the automaton is complete. :return: True if the automaton is complete, False otherwise. """ # all the state must have an outgoing transition. if not all(state in self._transition_function.keys() for state in self.states): return False for source in self._transition_function: guards = self._transition_function[source].values() negated_guards = Not(Or(*guards)) if satisfiable(negated_guards): return False return True
def compute_aliases(logic_expr, conditions_map): symbols_alias_map = {} unique_conditions_map = {} for symbol1 in set(get_symbols(logic_expr)): condition1 = conditions_map[symbol1] alias_found = False for symbol2, condition2 in unique_conditions_map.items(): if condition1 == condition2: symbols_alias_map[symbol1] = symbol2 alias_found = True break elif condition1.equals_negated(condition2): symbols_alias_map[symbol1] = Not(symbol2) alias_found = True break if not alias_found: unique_conditions_map[symbol1] = condition1 return symbols_alias_map
def test_count_ops_non_visual(): def count(val): return count_ops(val, visual=False) assert count(x) == 0 assert count(x) is not S.Zero assert count(x + y) == 1 assert count(x + y) is not S.One assert count(x + y*x + 2*y) == 4 assert count({x + y: x}) == 1 assert count({x + y: S(2) + x}) is not S.One assert count(Or(x,y)) == 1 assert count(And(x,y)) == 1 assert count(Not(x)) == 0 assert count(Nor(x,y)) == 1 assert count(Nand(x,y)) == 1 assert count(Xor(x,y)) == 3 assert count(Implies(x,y)) == 1 assert count(Equivalent(x,y)) == 1 assert count(ITE(x,y,z)) == 3 assert count(ITE(True,x,y)) == 0