Esempio n. 1
0
    def test_infix(self):
        ftype1 = FunctionType(REAL, [REAL])
        ftype2 = FunctionType(REAL, [REAL, INT])
        f = Symbol("f", ftype1)
        g = Symbol("g", ftype2)

        with self.assertRaises(PysmtModeError):
            f(1.0)

        get_env().enable_infix_notation = True

        infix = Equals(f(1.0), g(2.0, 4))
        explicit = Equals(Function(f, [Real(1.0)]),
                          Function(g, [Real(2.0), Int(4)]))
        self.assertEqual(infix, explicit)

        ftype1 = FunctionType(REAL, [BV16])
        ftype2 = FunctionType(BV16, [INT, BV16])
        f = Symbol("bvf", ftype1)
        g = Symbol("bvg", ftype2)
        infix = Equals(f(g(2, 6)), Real(0))
        explicit = Equals(Function(f, [Function(g, [Int(2), BV(6, 16)])]),
                          Real(0))
        self.assertEqual(infix, explicit)

        with self.assertRaises(PysmtValueError):
            f(BV(6, 16), BV(8, 16))

        ftype3 = FunctionType(REAL, [])
        h = Symbol("h", ftype3)
        with self.assertRaises(PysmtValueError):
            h()
Esempio n. 2
0
    def test_ackermannization_explicit(self):
        self.env.enable_infix_notation = True
        a, b = (Symbol(x, INT) for x in "ab")
        f, g = (Symbol(x, FunctionType(INT, [INT, INT])) for x in "fg")
        h = Symbol("h", FunctionType(INT, [INT]))

        formula1 = Not(Equals(f(a, g(a, h(a))), f(b, g(b, h(b)))))

        # Explicit the Ackermanization of this expression We end up
        # with a conjunction of implications that is then conjoined
        # with the original formula.
        ackermannization = Ackermannizer()
        actual_ack = ackermannization.do_ackermannization(formula1)

        terms_to_consts = ackermannization.get_term_to_const_dict()
        ack_h_a = terms_to_consts[h(a)]
        ack_h_b = terms_to_consts[h(b)]
        ack_g_a_h_a = terms_to_consts[g(a, h(a))]
        ack_g_b_h_b = terms_to_consts[g(b, h(b))]
        ack_f_a_g_a_h_a = terms_to_consts[f(a, g(a, h(a)))]
        ack_f_b_g_b_h_b = terms_to_consts[f(b, g(b, h(b)))]

        target_ack = And(
            Equals(a, b).Implies(Equals(ack_h_a, ack_h_b)),
            And(Equals(a, b),
                Equals(ack_h_a,
                       ack_h_b)).Implies(Equals(ack_g_a_h_a, ack_g_b_h_b)),
            And(Equals(a, b), Equals(ack_h_a, ack_h_b),
                Equals(ack_g_a_h_a, ack_g_b_h_b)).Implies(
                    Equals(ack_f_a_g_a_h_a, ack_f_b_g_b_h_b)))
        target_ack = And(target_ack,
                         Not(Equals(ack_f_a_g_a_h_a, ack_f_b_g_b_h_b)))
        self.assertValid(target_ack.Iff(actual_ack))
Esempio n. 3
0
    def test_get_value_of_function_bool(self):
        """Proper handling of models with functions with bool args."""
        hr = Symbol("hr", FunctionType(REAL, [BOOL, REAL, REAL]))
        hb = Symbol("hb", FunctionType(BOOL, [BOOL, REAL, REAL]))

        hr_0_1 = Function(hr, (TRUE(), Real(0), Real(1)))
        hb_0_1 = Function(hb, (TRUE(), Real(0), Real(1)))
        hbx = Function(hb, (Symbol("x"), Real(0), Real(1)))
        f = GT(hr_0_1, Real(0))
        g = hb_0_1

        for sname in get_env().factory.all_solvers(logic=QF_UFLIRA):
            with Solver(name=sname) as solver:
                # First hr
                solver.add_assertion(f)
                res = solver.solve()
                self.assertTrue(res)
                v = solver.get_value(hr_0_1)
                self.assertIsNotNone(solver.get_value(v))
                # Now hb
                solver.add_assertion(g)
                res = solver.solve()
                self.assertTrue(res)
                v = solver.get_value(hb_0_1)
                self.assertIsNotNone(v in [TRUE(), FALSE()])
                # Hbx
                solver.add_assertion(hbx)
                res = solver.solve()
                self.assertTrue(res)
                v = solver.get_value(hbx)
                self.assertIsNotNone(v in [TRUE(), FALSE()])
                # Get model
                model = solver.get_model()
                self.assertIsNotNone(model)
Esempio n. 4
0
    def test_multiple_declaration_w_same_functiontype(self):
        ft1 = FunctionType(REAL, [REAL])
        ft2 = FunctionType(REAL, [REAL])

        f1 = Symbol("f1", ft1)
        # The following raises an exception if not (ft1 == ft2)
        # since the same symbol has already been defined with
        # a "different" type.
        f1 = Symbol("f1", ft2)
Esempio n. 5
0
    def test_ackermannization_binary(self):
        self.env.enable_infix_notation = True
        a, b = (Symbol(x, INT) for x in "ab")
        f, g = (Symbol(x, FunctionType(INT, [INT, INT])) for x in "fg")
        h = Symbol("h", FunctionType(INT, [INT]))

        formula1 = Not(Equals(f(a, g(a, h(a))), f(b, g(b, h(b)))))

        formula2 = Equals(a, b)
        formula = And(formula1, formula2)
        self._verify_ackermannization(formula)
Esempio n. 6
0
    def test_euf(self):
        ftype1 = FunctionType(REAL, [REAL])
        ftype2 = FunctionType(REAL, [REAL, INT])

        f = Symbol("f", ftype1)
        g = Symbol("g", ftype2)

        check = Equals(Function(f, [Real(1)]), Function(g, (Real(2), Int(4))))

        self.assertSat(check, logic=UFLIRA,
                       msg="Formula was expected to be sat")
Esempio n. 7
0
    def test_check_types_in_constructors(self):
        with self.assertRaises(PysmtValueError):
            ArrayType(INT, BV)

        with self.assertRaises(PysmtValueError):
            ArrayType(BV, INT)

        with self.assertRaises(PysmtValueError):
            FunctionType(BV, (REAL, ))

        with self.assertRaises(PysmtValueError):
            FunctionType(REAL, (BV, ))
Esempio n. 8
0
    def test_function(self):
        f1_type = FunctionType(REAL, [REAL, REAL])
        f2_type = FunctionType(REAL, [])

        p, q = Symbol("p", REAL), Symbol("q", REAL)
        f1_symbol = Symbol("f1", f1_type)
        f2_symbol = Symbol("f2", f2_type)

        f1 = Function(f1_symbol, [p, q])
        f2 = Function(f2_symbol, [])

        f1_string = self.print_to_string(f1)
        f2_string = self.print_to_string(f2)

        self.assertEqual(f1_string, "(f1 p q)")
        self.assertEqual(f2_string, "(f2)")
Esempio n. 9
0
    def test_basic2(self):
        model_source = """\
(model
  ;; universe for U:
  ;;   (as @val1 U) (as @val0 U)
  (define-fun b () U
    (as @val0 U))
  (define-fun a () U
    (as @val1 U))
  (define-fun f ((x!0 U)) U
    (ite (= x!0 (as @val1 U)) (as @val0 U)
      (as @val1 U)))
)
"""
        model_buf = StringIO(model_source)

        parser = SmtLibParser()
        simplifier = SmtLibModelValidationSimplifier(self.env)

        U = self.tm.Type('U', 0)

        # We construct the model even befor symbols are constructed in pysmt
        model, interpretations = parser.parse_model(model_buf)

        a = self.fm.Symbol('a', U)
        b = self.fm.Symbol('b', U)
        f = self.fm.Symbol('f', FunctionType(U, [U]))
        formula = self.fm.And(self.fm.Not(self.fm.Equals(a, b)),
                              self.fm.Equals(self.fm.Function(f, [a]), b))

        simp = simplifier.simplify(formula.substitute(model, interpretations))
        self.assertEqual(simp, self.fm.TRUE())
Esempio n. 10
0
    def _get_basic_type(self, type_name, params=None):
        """
        Returns the pysmt type representation for the given type name.
        If params is specified, the type is interpreted as a function type.
        """
        if params is None or len(params) == 0:
            if isinstance(type_name, tuple):
                assert len(type_name) == 3
                assert type_name[0] == "Array"
                return ArrayType(self._get_basic_type(type_name[1]),
                                 self._get_basic_type(type_name[2]))

            if type_name == "Bool":
                return BOOL
            elif type_name == "Int":
                return INT
            elif type_name == "Real":
                return REAL
            elif type_name.startswith("BV"):
                size = int(type_name[2:])
                return BVType(size)
            else:
                res = self.cache.get(type_name)
                if res is not None:
                    res = self._get_basic_type(res)
                return res
        else:
            rt = self._get_basic_type(type_name)
            pt = [self._get_basic_type(par) for par in params]
            return FunctionType(rt, pt)
Esempio n. 11
0
    def test_normalization(self):
        from pysmt.environment import Environment

        env2 = Environment()
        mgr2 = env2.formula_manager

        ty = ArrayType(BOOL, REAL)
        x = FreshSymbol(ty)
        fty = FunctionType(BOOL, (ty, ))
        f = FreshSymbol(fty)
        g = Function(f, (x, ))
        self.assertIsNotNone(g)
        self.assertNotIn(g, mgr2)
        g2 = mgr2.normalize(g)
        self.assertIn(g2, mgr2)
        # Since the types are from two different environments, they
        # should be different.
        x2 = g2.arg(0)
        ty2 = x2.symbol_type()
        self.assertFalse(ty2 is ty, ty)
        fname = g2.function_name()
        fty2 = fname.symbol_type()
        self.assertFalse(fty2 is fty, fty)

        # Test ArrayValue
        h = Array(BVType(4), BV(0, 4))
        h2 = mgr2.normalize(h)
        self.assertEqual(h.array_value_index_type(),
                         h2.array_value_index_type())
        self.assertFalse(h.array_value_index_type() is \
                         h2.array_value_index_type())
Esempio n. 12
0
    def test_substituter_conditions(self):
        x = Symbol("x")
        y = Symbol("y")
        and_x_x = And(x, x)
        ftype = FunctionType(BOOL, [BOOL])
        f = Symbol("f", ftype)

        # 1. All arguments must be terms
        args_good = {x: y}
        args_bad = {x: f}

        substitute(and_x_x, args_good)
        with self.assertRaisesRegex(TypeError, " substitutions"):
            substitute(and_x_x, args_bad)

        # 2. All arguments belong to the manager of the substituter.
        new_mgr = FormulaManager(get_env())
        new_x = new_mgr.Symbol("x")
        self.assertNotEqual(x, new_x)
        args_1 = {x: new_x}
        args_2 = {new_x: new_x}

        with self.assertRaisesRegex(TypeError, "Formula Manager"):
            substitute(and_x_x, args_1)

        with self.assertRaisesRegex(TypeError, "Formula Manager."):
            substitute(and_x_x, args_2)

        with self.assertRaisesRegex(TypeError, "substitute()"):
            substitute(f, {x: x})
Esempio n. 13
0
    def test_function(self):
        f1_type = FunctionType(REAL, [REAL, REAL])
        f2_type = FunctionType(REAL, [])

        p, q = Symbol("p", REAL), Symbol("q", REAL)
        f1_symbol = Symbol("f1", f1_type)
        f2_symbol = Symbol("f2", f2_type)

        f1 = Function(f1_symbol, [p, q])
        f2 = Function(f2_symbol, [])

        self.assertEqual(f1.to_smtlib(daggify=False), "(f1 p q)")
        self.assertEqual(f2.to_smtlib(daggify=False), "f2")

        self.assertEqual(f1.to_smtlib(daggify=True),
                         "(let ((.def_0 (f1 p q))) .def_0)")
        self.assertEqual(f2.to_smtlib(daggify=True), "f2")
Esempio n. 14
0
    def test_infix_with_function(self):
        mgr = self.env.formula_manager
        self.env.enable_infix_notation = True

        ftype = FunctionType(BV128, (BV32, ))
        g = mgr.Symbol("g", ftype)
        f = mgr.Function(g, (mgr.BV(1, 32), ))
        self.assertEqual(f.Equals(5), f.Equals(mgr.BV(5, 128)))
Esempio n. 15
0
    def test_theory_oracle_on_functions(self):
        from pysmt.logics import QF_UFIDL

        mgr = self.env.formula_manager
        ftype = FunctionType(INT, (BOOL, ))
        f = mgr.Symbol("f", ftype)
        f_1 = mgr.Function(f, (mgr.TRUE(), ))
        theory = self.env.theoryo.get_theory(f_1)
        self.assertEqual(theory, QF_UFIDL.theory)
Esempio n. 16
0
    def to_sbv(self, size: int) -> SMTBitVector:
        cls = type(self)
        ufs = _uf_table[cls]['to_usbv']
        if size not in ufs:
            name = '.'.join((cls.__name__, f'to_sbv[{size}]'))
            ufs[size] = shortcuts.Symbol(
                name, FunctionType(BVType(size), (BVType(self.size), )))

        return SMTBitVector[size](ufs[size](self._value))
Esempio n. 17
0
 def test_0arity_function(self):
     # Calling FunctionType on a 0-arity list of parameters returns
     # the type itself.
     t = FunctionType(REAL, [])
     # After this call: t = REAL
     # s1 is a symbol of type real
     s1 = self.mgr.Symbol("s1", t)
     s1b = self.mgr.Function(s1, [])
     self.assertEqual(s1, s1b)
Esempio n. 18
0
 def test_ackermannization_pairwise(self):
     self.env.enable_infix_notation = True
     a, b, c, d = (Symbol(x, INT) for x in "abcd")
     f = Symbol("f", FunctionType(INT, [INT]))
     formula = And(Not(Equals(f(b), f(c))), Equals(f(a), f(b)),
                   Equals(f(c), f(d)), Equals(a, d))
     self.assertUnsat(formula)
     formula_ack = Ackermannizer().do_ackermannization(formula)
     self.assertUnsat(formula_ack)
Esempio n. 19
0
    def test_simplify(self):
        ftype1 = FunctionType(REAL, [REAL, REAL])

        plus = Symbol("plus", ftype1)
        x = Symbol('x', REAL)
        y = Symbol('y', REAL)
        z = Symbol('z', REAL)

        f = Function(plus, (Minus(Real(5), Real(5)), Plus(y, Minus(z, z))))
        self.assertEqual(Function(plus, (Real(0), y)), f.simplify())
Esempio n. 20
0
    def test_functions(self):
        vi = Symbol("At", INT)
        vr = Symbol("Bt", REAL)

        f = Symbol("f", FunctionType(INT, [REAL]))
        g = Symbol("g", FunctionType(REAL, [INT]))

        tc = get_env().stc

        self.assertEqual(tc.walk(Function(f, [vr])), INT)
        self.assertEqual(tc.walk(Function(g, [vi])), REAL)
        self.assertEqual(tc.walk(Function(f, [Function(g, [vi])])), INT)
        self.assertEqual(tc.walk(LE(Plus(vi, Function(f, [Real(4)])), Int(8))), BOOL)
        self.assertEqual(tc.walk(LE(Plus(vr, Function(g, [Int(4)])), Real(8))), BOOL)

        with self.assertRaises(PysmtTypeError):
            LE(Plus(vr, Function(g, [Real(4)])), Real(8))

        with self.assertRaises(PysmtTypeError):
            LE(Plus(vi, Function(f, [Int(4)])), Int(8))
Esempio n. 21
0
 def add_pred(self, formula, name):
     args = []
     types = []
     if formula.is_quantifier():
         for a in formula.quantifier_vars():
             args.append(a)
             types.append(a.symbol_type())
         formula = formula.arg(0)
     ft = FunctionType(BOOL, tuple(types))
     f = Symbol(name, ft)
     lhs = Function(f, args)
     self._predicates[lhs] = formula
Esempio n. 22
0
    def test_uflira(self):
        a = Symbol("a", REAL)
        b = Symbol("b", INT)
        h = Symbol("ih", FunctionType(REAL, [REAL, INT]))

        # ( ToReal(b) = a /\ h(ToReal(b), b) >= 3) -> (h(a,b) >= 0)
        check = Implies(
            And(Equals(ToReal(b), a), GE(Function(h, (ToReal(b), b)),
                                         Real(3))),
            GE(Function(h, (a, b)), Real(0)))

        for sname in get_env().factory.all_solvers(logic=UFLIRA):
            self.assertTrue(is_valid(check, solver_name=sname))
Esempio n. 23
0
    def __init_subclass__(cls):
        _uf_table[cls] = ufs = dict()
        T = BVType(cls.size)
        for method_name, *args in _SIGS:
            args = [T if x is None else x for x in args]
            rtype = args[-1]
            params = args[:-1]
            name = '.'.join((cls.__name__, method_name))
            ufs[method_name] = shortcuts.Symbol(name,
                                                FunctionType(rtype, params))

        ufs['to_sbv'] = dict()
        ufs['to_ubv'] = dict()
Esempio n. 24
0
    def test_ackermannization_dictionaries(self):
        self.env.enable_infix_notation = True
        a, b = (Symbol(x, INT) for x in "ab")
        f, g = (Symbol(x, FunctionType(INT, [INT, INT])) for x in "fg")
        h = Symbol("h", FunctionType(INT, [INT]))

        formula1 = Not(Equals(f(a, g(a, h(a))), f(b, g(b, h(b)))))
        formula2 = Equals(a, b)
        formula = And(formula1, formula2)
        ackermannization = Ackermannizer()
        _ = ackermannization.do_ackermannization(formula)
        terms_to_consts = ackermannization.get_term_to_const_dict()
        consts_to_terms = ackermannization.get_const_to_term_dict()
        # The maps have the same length
        self.assertEqual(len(terms_to_consts), len(consts_to_terms))
        # The maps are the inverse of each other
        for t in terms_to_consts:
            self.assertEqual(t, consts_to_terms[terms_to_consts[t]])
        # Check that the the functions are there
        for atom in formula.get_atoms():
            if atom.is_function_application():
                self.assertIsNotNone(terms_to_consts[atom])
Esempio n. 25
0
    def test_get_value_of_function(self):
        """get_value on a function should raise an exception."""
        h = Symbol("h", FunctionType(REAL, [REAL, REAL]))

        h_0_0 = Function(h, (Real(0), Real(1)))
        f = GT(h_0_0, Real(0))
        for sname in get_env().factory.all_solvers(logic=QF_UFLIRA):
            with Solver(name=sname) as solver:
                solver.add_assertion(f)
                res = solver.solve()
                self.assertTrue(res)
                with self.assertRaises(PysmtTypeError):
                    solver.get_value(h)
                self.assertIsNotNone(solver.get_value(h_0_0))
Esempio n. 26
0
    def test_substitution_on_functions(self):
        i, r = FreshSymbol(INT), FreshSymbol(REAL)
        f = Symbol("f", FunctionType(BOOL, [INT, REAL]))

        phi = Function(f, [Plus(i, Int(1)), Minus(r, Real(2))])

        phi_sub = substitute(phi, {i: Int(0)}).simplify()
        self.assertEqual(phi_sub, Function(f, [Int(1), Minus(r, Real(2))]))

        phi_sub = substitute(phi, {r: Real(0)}).simplify()
        self.assertEqual(phi_sub, Function(f, [Plus(i, Int(1)), Real(-2)]))

        phi_sub = substitute(phi, {r: Real(0), i: Int(0)}).simplify()
        self.assertEqual(phi_sub, Function(f, [Int(1), Real(-2)]))
Esempio n. 27
0
 def _get_basic_type(self, type_name, params):
     """
     Returns the pysmt type representation for the given type name.
     If params is specified, the type is interpreted as a function type.
     """
     if len(params) == 0:
         if type_name == "Bool":
             return BOOL
         if type_name == "Int":
             return INT
         elif type_name == "Real":
             return REAL
     else:
         rt = self._get_basic_type(type_name, [])
         pt = [self._get_basic_type(par, []) for par in params]
         return FunctionType(rt, pt)
Esempio n. 28
0
    def test_quantified_euf(self):
        ftype1 = FunctionType(REAL, [REAL, REAL])

        plus = Symbol("plus", ftype1)
        x = Symbol('x', REAL)
        y = Symbol('y', REAL)
        z = Symbol('z', REAL)

        axiom = ForAll([x, y], Equals(Function(plus, (x, y)), Plus(x, y)))

        test1 = Equals(Plus(z, Real(4)), Function(plus, (Real(4), z)))
        test2 = Equals(Function(plus, (Real(5), Real(4))), Real(9))

        check = Implies(axiom, And(test1, test2))

        self.assertValid(check, logic=UFLRA,
                        msg="Formula was expected to be valid")
Esempio n. 29
0
 def _get_basic_type(self, type_name, params=None):
     """
     Returns the pysmt type representation for the given type name.
     If params is specified, the type is interpreted as a function type.
     """
     if params is None or len(params) == 0:
         if type_name == "Bool":
             return BOOL
         elif type_name == "Int":
             return INT
         elif type_name == "Real":
             return REAL
         elif type_name.startswith("BV"):
             size = int(type_name[2:])
             return BVType(size)
     else:
         rt = self._get_basic_type(type_name)
         pt = [self._get_basic_type(par) for par in params]
         return FunctionType(rt, pt)
Esempio n. 30
0
    def setUp(self):
        super(TestFormulaManager, self).setUp()

        self.env = get_env()
        self.mgr = self.env.formula_manager

        self.x = self.mgr.Symbol("x")
        self.y = self.mgr.Symbol("y")

        self.p = self.mgr.Symbol("p", INT)
        self.q = self.mgr.Symbol("q", INT)
        self.r = self.mgr.Symbol("r", REAL)
        self.s = self.mgr.Symbol("s", REAL)
        self.rconst = self.mgr.Real(10)
        self.iconst = self.mgr.Int(10)

        self.ftype = FunctionType(REAL, [REAL, REAL])
        self.f = self.mgr.Symbol("f", self.ftype)

        self.real_expr = self.mgr.Plus(self.s, self.r)