Ejemplo n.º 1
0
    def test_propagate_toplevel(self):
        x = Symbol("x", REAL)
        y = Symbol("y", REAL)

        f = And(LT(Real(4), Times(x, x)), Equals(Real(1), x))
        fp = propagate_toplevel(f)
        self.assertTrue(fp.is_false())
        if self.env.factory.has_solvers(logic=QF_NRA):
            try:
                ok = is_valid(Iff(f, fp))
            except SolverReturnedUnknownResultError:
                ok = not logic.quantifier_free
            self.assertTrue(ok)
        
        f = And(LT(Real(4), Times(x, x)), Equals(y, x), Equals(y, Real(1)))
        fp = propagate_toplevel(f)
        self.assertTrue(fp.is_false())
        if self.env.factory.has_solvers(logic=QF_NRA):
            try:
                ok = is_valid(Iff(f, fp))
            except SolverReturnedUnknownResultError:
                ok = not logic.quantifier_free
            self.assertTrue(ok)

        f = And(Equals(Real(4), x), Equals(y, x), Equals(y, Real(0)))
        fp = propagate_toplevel(f)
        self.assertTrue(fp.is_false())
        fp = propagate_toplevel(f, preserve_equivalence=False)
        self.assertTrue(fp.is_false())
        fp = propagate_toplevel(f, preserve_equivalence=False, do_simplify=False)
        self.assertTrue(fp.is_false())

        f = Equals(Real(4), Real(5))
        fp = propagate_toplevel(f, do_simplify=False)
        self.assertTrue(fp.is_false())
Ejemplo n.º 2
0
 def test_conversion_of_fractions_in_z3(self):
     self.assertTrue(
         is_valid(Equals(Real(Fraction(1, 9)), Div(Real(1), Real(9))),
                  solver_name="msat"))
     self.assertTrue(
         is_valid(Equals(Real(Fraction(1, 9)), Div(Real(1), Real(9))),
                  solver_name="z3"))
Ejemplo n.º 3
0
    def test_examples_z3(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            v = is_valid(f, solver_name='z3', logic=logic)
            s = is_sat(f, solver_name='z3', logic=logic)

            self.assertEqual(validity, v, f)
            self.assertEqual(satisfiability, s, f)
Ejemplo n.º 4
0
 def _validate(self, old, new):
     if self.validate_simplifications:
         Iff = self.env.formula_manager.Iff
         is_valid = self.env.factory.is_valid
         sname = self._validation_sname
         assert is_valid(Iff(old, new), solver_name=sname ), \
           "Was: %s \n Obtained: %s\n" % (str(old), str(new))
Ejemplo n.º 5
0
 def _validate(self, old, new):
     if self.validate_simplifications:
         Iff = self.env.formula_manager.Iff
         is_valid = self.env.factory.is_valid
         sname = self._validation_sname
         assert is_valid(Iff(old, new), solver_name=sname ), \
           "Was: %s \n Obtained: %s\n" % (str(old), str(new))
Ejemplo n.º 6
0
    def test_examples_z3(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            v = is_valid(f, solver_name='z3', logic=logic)
            s = is_sat(f, solver_name='z3', logic=logic)

            self.assertEqual(validity, v, f)
            self.assertEqual(satisfiability, s, f)
Ejemplo n.º 7
0
    def test_examples_by_logic(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            if len(get_env().factory.all_solvers(logic=logic)) > 0:
                v = is_valid(f, logic=logic)
                s = is_sat(f, logic=logic)

                self.assertEqual(validity, v, f.serialize())
                self.assertEqual(satisfiability, s, f.serialize())
Ejemplo n.º 8
0
    def test_examples_yices(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            if not logic.quantifier_free: continue
            v = is_valid(f, solver_name='yices', logic=logic)
            s = is_sat(f, solver_name='yices', logic=logic)

            self.assertEqual(validity, v, f)
            self.assertEqual(satisfiability, s, f)
Ejemplo n.º 9
0
    def test_examples_by_logic(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            if len(get_env().factory.all_solvers(logic=logic)) > 0:
                v = is_valid(f, logic=logic)
                s = is_sat(f, logic=logic)

                self.assertEqual(validity, v, f.serialize())
                self.assertEqual(satisfiability, s, f.serialize())
Ejemplo n.º 10
0
    def test_examples_yices(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            if not logic.quantifier_free: continue
            v = is_valid(f, solver_name='yices', logic=logic)
            s = is_sat(f, solver_name='yices', logic=logic)

            self.assertEqual(validity, v, f)
            self.assertEqual(satisfiability, s, f)
Ejemplo n.º 11
0
 def test_nnf_examples(self):
     for (f, _, _, logic) in get_example_formulae():
         if get_env().factory.has_solvers(logic=logic):
             rf = nnf(f)
             try:
                 ok = is_valid(Iff(f, rf), logic=logic)
             except SolverReturnedUnknownResultError:
                 ok = not logic.quantifier_free
             self.assertTrue(ok)
Ejemplo n.º 12
0
    def _std_examples(self, qe, target_logic):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            if logic != target_logic: continue
            qf = qe.eliminate_quantifiers(f)
            s = is_sat(qf)
            v = is_valid(qf)

            self.assertEqual(validity, v, f)
            self.assertEqual(satisfiability, s, f)
Ejemplo n.º 13
0
    def _std_examples(self, qe, target_logic):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            if logic != target_logic: continue
            qf = qe.eliminate_quantifiers(f)
            s = is_sat(qf)
            v = is_valid(qf)

            self.assertEqual(validity, v, f)
            self.assertEqual(satisfiability, s, f)
Ejemplo n.º 14
0
 def test_disj_partitioning(self):
     for (f, _, _, logic) in get_example_formulae():
         if self.env.factory.has_solvers(logic=logic):
             disjuncts = list(disjunctive_partition(f))
             try:
                 ok = is_valid(Iff(f, Or(disjuncts)), logic=logic)
             except SolverReturnedUnknownResultError:
                 ok = not logic.quantifier_free
             self.assertTrue(ok)
Ejemplo n.º 15
0
 def test_conj_partitioning(self):
     for (f, _, _, logic) in get_example_formulae():
         if get_env().factory.has_solvers(logic=logic):
             conjuncts = list(conjunctive_partition(f))
             try:
                 ok = is_valid(Iff(f, And(conjuncts)), logic=logic)
             except SolverReturnedUnknownResultError:
                 ok = not logic.quantifier_free
             self.assertTrue(ok)
Ejemplo n.º 16
0
 def test_aig_examples(self):
     for (f, _, _, logic) in get_example_formulae():
         if self.env.factory.has_solvers(logic=logic):
             f_aig = aig(f)
             try:
                 ok = is_valid(Iff(f, f_aig), logic=logic)
             except SolverReturnedUnknownResultError:
                 ok = not logic.quantifier_free
             self.assertTrue(ok, "Was: %s\n Got:%s" % (f, f_aig))
Ejemplo n.º 17
0
 def test_propagate_toplevel_examples(self):
     for (f, _, _, logic) in get_example_formulae():
         if self.env.factory.has_solvers(logic=logic):
             rwf = propagate_toplevel(f)
             try:
                 ok = is_valid(Iff(f, rwf), logic=logic)
             except SolverReturnedUnknownResultError:
                 ok = not logic.quantifier_free
             self.assertTrue(ok)
Ejemplo n.º 18
0
 def test_nnf_examples(self):
     for (f, _, _, logic) in get_example_formulae():
         if get_env().factory.has_solvers(logic=logic):
             rf = nnf(f)
             try:
                 ok = is_valid(Iff(f, rf), logic=logic)
             except SolverReturnedUnknownResultError:
                 ok = not logic.quantifier_free
             self.assertTrue(ok)
Ejemplo n.º 19
0
 def test_prenex_examples(self):
     for (f, _, _, logic) in get_example_formulae():
         if self.env.factory.has_solvers(logic=logic):
             prenex = prenex_normal_form(f)
             try:
                 ok = is_valid(Iff(f, prenex), logic=logic)
             except SolverReturnedUnknownResultError:
                 ok = not logic.quantifier_free
             self.assertTrue(ok)
Ejemplo n.º 20
0
 def test_prenex_examples(self):
     for (f, _, _, logic) in get_example_formulae():
         if self.env.factory.has_solvers(logic=logic):
             prenex = prenex_normal_form(f)
             try:
                 ok = is_valid(Iff(f, prenex), logic=logic)
             except SolverReturnedUnknownResultError:
                 ok = not logic.quantifier_free
             self.assertTrue(ok)
Ejemplo n.º 21
0
 def test_aig_examples(self):
     for (f, _, _, logic) in get_example_formulae():
         if get_env().factory.has_solvers(logic=logic):
             f_aig = aig(f)
             try:
                 ok = is_valid(Iff(f, f_aig), logic=logic)
             except SolverReturnedUnknownResultError:
                 ok = not logic.quantifier_free
             self.assertTrue(ok, "Was: %s\n Got:%s" % (f, f_aig))
Ejemplo n.º 22
0
 def test_propagate_toplevel_examples(self):
    for (f, _, _, logic) in get_example_formulae():
         if self.env.factory.has_solvers(logic=logic):
             rwf = propagate_toplevel(f)
             try:
                 ok = is_valid(Iff(f, rwf), logic=logic)
             except SolverReturnedUnknownResultError:
                 ok = not logic.quantifier_free
             self.assertTrue(ok)
Ejemplo n.º 23
0
 def test_examples_btor(self):
     for (f, validity, satisfiability, logic) in get_example_formulae():
         if not logic.quantifier_free: continue
         try:
             v = is_valid(f, solver_name='btor', logic=logic)
             s = is_sat(f, solver_name='btor', logic=logic)
             self.assertEqual(validity, v, f)
             self.assertEqual(satisfiability, s, f)
         except NoSolverAvailableError:
             pass  #Skip tests for unsupported logic
Ejemplo n.º 24
0
    def test_examples_msat(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            if not logic.quantifier_free: continue
            if not logic.theory.linear: continue
            if logic.theory.strings: continue

            v = is_valid(f, solver_name='msat', logic=logic)
            s = is_sat(f, solver_name='msat', logic=logic)
            self.assertEqual(validity, v, f)
            self.assertEqual(satisfiability, s, f)
Ejemplo n.º 25
0
    def test_examples_msat(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            if not logic.quantifier_free: continue
            if not logic.theory.linear: continue
            if logic.theory.strings: continue

            v = is_valid(f, solver_name='msat', logic=logic)
            s = is_sat(f, solver_name='msat', logic=logic)
            self.assertEqual(validity, v, f)
            self.assertEqual(satisfiability, s, f)
Ejemplo n.º 26
0
 def test_examples_btor(self):
     for (f, validity, satisfiability, logic) in get_example_formulae():
         if not logic.quantifier_free: continue
         try:
             v = is_valid(f, solver_name='btor', logic=logic)
             s = is_sat(f, solver_name='btor', logic=logic)
             self.assertEqual(validity, v, f)
             self.assertEqual(satisfiability, s, f)
         except NoSolverAvailableError:
             pass #Skip tests for unsupported logic
Ejemplo n.º 27
0
    def test_examples_btor(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            if not logic.quantifier_free: continue
            if logic.theory.strings: continue
            if logic.theory.integer_arithmetic: continue
            if logic.theory.real_arithmetic: continue
            if logic.theory.custom_type: continue

            v = is_valid(f, solver_name='btor', logic=logic)
            s = is_sat(f, solver_name='btor', logic=logic)
            self.assertEqual(validity, v, f)
            self.assertEqual(satisfiability, s, f)
Ejemplo n.º 28
0
    def test_simplify_qf_msat(self):
        """ Test simplifier on quantifier free random formula using MathSAT"""
        for i in xrange(MANY_ITERATIONS):
            f = build_random_qf_formula(10, 20, 4, 0.1, seed=i)
            sf = f.simplify()
            test = Iff(f, sf)
            res = is_valid(test, solver_name='msat')

            self.assertTrue(
                res, "Simplification of formula %d " % i +
                "did not provide equivalent " + "result:\n f= %s\n sf = %s" %
                (f, sf))
Ejemplo n.º 29
0
    def test_examples_z3(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            try:
                v = is_valid(f, solver_name='z3', logic=logic)
                s = is_sat(f, solver_name='z3', logic=logic)

                self.assertEqual(validity, v, f)
                self.assertEqual(satisfiability, s, f)
            except NoSolverAvailableError:
                # Trying to solve a logic that mathsat does not support
                theory = logic.theory
                assert theory.strings
Ejemplo n.º 30
0
    def test_examples_z3(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            try:
                v = is_valid(f, solver_name='z3', logic=logic)
                s = is_sat(f, solver_name='z3', logic=logic)

                self.assertEqual(validity, v, f)
                self.assertEqual(satisfiability, s, f)
            except NoSolverAvailableError:
                # Trying to solve a logic that mathsat does not support
                theory = logic.theory
                assert theory.strings
Ejemplo n.º 31
0
    def test_examples_btor(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            if not logic.quantifier_free: continue
            if logic.theory.strings: continue
            if logic.theory.integer_arithmetic: continue
            if logic.theory.real_arithmetic: continue
            if logic.theory.custom_type: continue

            v = is_valid(f, solver_name='btor', logic=logic)
            s = is_sat(f, solver_name='btor', logic=logic)
            self.assertEqual(validity, v, f)
            self.assertEqual(satisfiability, s, f)
Ejemplo n.º 32
0
    def test_msat_back_formulae(self):
        from pysmt.solvers.msat import MathSAT5Solver, MSatConverter

        env = get_env()
        msat = MathSAT5Solver(environment=env, logic=QF_UFLIRA)
        new_converter = MSatConverter(env, msat.msat_env)

        for formula, _, _, logic in get_example_formulae():
            if logic.quantifier_free:
                term = new_converter.convert(formula)
                res = new_converter.back(term)
                self.assertTrue(is_valid(Iff(formula, res), logic=QF_UFLIRA))
Ejemplo n.º 33
0
    def test_plus_converts_correctly_n_ary_functions(self):
        """Handling of Plus n-ary functionality.

        Only the first two elements were translated to the solver
        """

        a = Symbol("a", REAL)
        b = Symbol("b", REAL)
        c = Symbol("c", REAL)

        p1 = Plus(
            a,
            Real((1, 6)),
            b,
            c,
        )
        p2 = Plus(a, b, c, Real((1, 6)))

        self.assertTrue(is_valid(Equals(p1, p2)))
        self.assertTrue(is_valid(Equals(p1, p2), solver_name='z3'))
        self.assertTrue(is_valid(Equals(p1, p2), solver_name='msat'))
Ejemplo n.º 34
0
    def test_examples_cvc4(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            try:
                if not logic.quantifier_free: continue
                v = is_valid(f, solver_name='cvc4', logic=logic)
                s = is_sat(f, solver_name='cvc4', logic=logic)

                self.assertEqual(validity, v, f)
                self.assertEqual(satisfiability, s, f)

            except SolverReturnedUnknownResultError:
                # CVC4 does not handle quantifiers in a complete way
                self.assertFalse(logic.quantifier_free)
Ejemplo n.º 35
0
    def test_encode_vars(self):
        fmwk_over = TestGrounding._get_fmwkov("", "cb", False)
        trace = CTrace()

        fmwk_over_cb = TestGrounding._get_fmwkov("", "cb", False)
        fmwk_over_cb1 = TestGrounding._get_fmwkov("", "cb1", False)

        cb = CCallback(1, 1, "", "cb", [], None, [fmwk_over_cb])
        cb1 = CCallback(1, 1, "", "cb1", [], None, [fmwk_over_cb1])
        ci = CCallin(1, 1, "", "ci", [], None)
        cb.add_msg(cb1)
        cb1.add_msg(ci)
        trace.add_msg(cb)

        cb = CCallback(1, 1, "", "cb", [], None, [fmwk_over_cb])
        cb1 = CCallback(1, 1, "", "cb1", [], None, [fmwk_over_cb1])
        ci = CCallin(1, 1, "", "ci", [], None)
        cb.add_msg(cb1)
        cb1.add_msg(ci)
        trace.add_msg(cb)

        ts_enc = TSEncoder(trace, [])

        ts_var = ts_enc._encode_vars()

        self.assertTrue(len(ts_var.state_vars) == 6)

        trans = TRUE()
        l = [cb, cb1, ci]
        for m in l:
            for entry in [TSEncoder.ENTRY, TSEncoder.EXIT]:
                var = TSEncoder._get_state_var(
                    TSEncoder.get_key_from_msg(m, entry))
                ivar = ts_enc.r2a.get_msg_eq(
                    TSEncoder.get_key_from_msg(m, entry))
                trans = And(trans, Implies(ivar, var))

        self.assertTrue(is_valid(Iff(ts_var.init, TRUE())))
        self.assertTrue(is_valid(Iff(ts_var.trans, trans)))
Ejemplo n.º 36
0
    def test_examples_cvc4(self):
        for (f, validity, satisfiability, logic) in get_example_formulae():
            try:
                if not logic.quantifier_free: continue
                v = is_valid(f, solver_name='cvc4', logic=logic)
                s = is_sat(f, solver_name='cvc4', logic=logic)

                self.assertEqual(validity, v, f)
                self.assertEqual(satisfiability, s, f)

            except SolverReturnedUnknownResultError:
                # CVC4 does not handle quantifiers in a complete way
                self.assertFalse(logic.quantifier_free)
Ejemplo n.º 37
0
    def test_examples(self):
        for n in self.all_solvers:
            with Solver(name=n) as solver:
                for (f, validity, satisfiability, logic) in \
                    get_example_formulae():
                    try:
                        get_closer_logic(solver.LOGICS, logic)
                    except NoLogicAvailableError:
                        continue
                    v = is_valid(f, solver_name=n, logic=logic)
                    s = is_sat(f, solver_name=n, logic=logic)

                    self.assertEqual(validity, v, f)
                    self.assertEqual(satisfiability, s, f)
Ejemplo n.º 38
0
 def test_examples_by_logic(self):
     for (f, validity, satisfiability, logic) in get_example_formulae():
         if len(get_env().factory.all_solvers(logic=logic)) > 0:
             try:
                 v = is_valid(f, logic=logic)
                 s = is_sat(f, logic=logic)
                 self.assertEqual(validity, v, f.serialize())
                 self.assertEqual(satisfiability, s, f.serialize())
             except SolverReturnedUnknownResultError:
                 s = Solver(logic=logic)
                 print(s, logic, f.serialize())
                 self.assertFalse(logic.quantifier_free,
                                  "Unkown result are accepted only on "\
                                  "Quantified formulae")
Ejemplo n.º 39
0
 def test_examples_by_logic(self):
     for (f, validity, satisfiability, logic) in get_example_formulae():
         if len(get_env().factory.all_solvers(logic=logic)) > 0:
             try:
                 v = is_valid(f, logic=logic)
                 s = is_sat(f, logic=logic)
                 self.assertEqual(validity, v, f.serialize())
                 self.assertEqual(satisfiability, s, f.serialize())
             except SolverReturnedUnknownResultError:
                 s = Solver(logic=logic)
                 print(s, logic, f)
                 self.assertFalse(logic.quantifier_free,
                                  "Unkown result are accepted only on "\
                                  "Quantified formulae")
Ejemplo n.º 40
0
    def test_propagate_toplevel(self):
        x = Symbol("x", REAL)
        y = Symbol("y", REAL)

        f = And(LT(Real(4), Times(x, x)), Equals(Real(1), x))
        fp = propagate_toplevel(f)
        self.assertTrue(fp.is_false())
        if self.env.factory.has_solvers(logic=QF_NRA):
            try:
                ok = is_valid(Iff(f, fp))
            except SolverReturnedUnknownResultError:
                ok = not logic.quantifier_free
            self.assertTrue(ok)

        f = And(LT(Real(4), Times(x, x)), Equals(y, x), Equals(y, Real(1)))
        fp = propagate_toplevel(f)
        self.assertTrue(fp.is_false())
        if self.env.factory.has_solvers(logic=QF_NRA):
            try:
                ok = is_valid(Iff(f, fp))
            except SolverReturnedUnknownResultError:
                ok = not logic.quantifier_free
            self.assertTrue(ok)

        f = And(Equals(Real(4), x), Equals(y, x), Equals(y, Real(0)))
        fp = propagate_toplevel(f)
        self.assertTrue(fp.is_false())
        fp = propagate_toplevel(f, preserve_equivalence=False)
        self.assertTrue(fp.is_false())
        fp = propagate_toplevel(f,
                                preserve_equivalence=False,
                                do_simplify=False)
        self.assertTrue(fp.is_false())

        f = Equals(Real(4), Real(5))
        fp = propagate_toplevel(f, do_simplify=False)
        self.assertTrue(fp.is_false())
Ejemplo n.º 41
0
 def test_examples_cvc4(self):
     for (f, validity, satisfiability, logic) in get_example_formulae():
         if not logic.theory.linear: continue
         if logic.theory.arrays_const: continue
         try:
             v = is_valid(f, solver_name='cvc4', logic=logic)
             s = is_sat(f, solver_name='cvc4', logic=logic)
             self.assertEqual(validity, v, f)
             self.assertEqual(satisfiability, s, f)
         except SolverReturnedUnknownResultError:
             # CVC4 does not handle quantifiers in a complete way
             self.assertFalse(logic.quantifier_free)
         except NoSolverAvailableError:
             # Logic is not supported by CVC4
             pass
Ejemplo n.º 42
0
 def test_examples_cvc4(self):
     for (f, validity, satisfiability, logic) in get_example_formulae():
         if not logic.theory.linear: continue
         if logic.theory.arrays_const: continue
         try:
             v = is_valid(f, solver_name='cvc4', logic=logic)
             s = is_sat(f, solver_name='cvc4', logic=logic)
             self.assertEqual(validity, v, f)
             self.assertEqual(satisfiability, s, f)
         except SolverReturnedUnknownResultError:
             # CVC4 does not handle quantifiers in a complete way
             self.assertFalse(logic.quantifier_free)
         except NoSolverAvailableError:
             # Logic is not supported by CVC4
             pass
Ejemplo n.º 43
0
    def test_examples(self):
        for n in self.all_solvers:
            with Solver(name=n) as solver:
                print("Solver %s : %s" % (n, solver.LOGICS))
                for (f, validity, satisfiability, logic) in \
                    get_example_formulae():
                    try:
                        get_closer_logic(solver.LOGICS, logic)
                    except NoLogicAvailableError:
                        continue
                    print(f)
                    v = is_valid(f, solver_name=n, logic=logic)
                    s = is_sat(f, solver_name=n, logic=logic)

                    self.assertEqual(validity, v, f)
                    self.assertEqual(satisfiability, s, f)
Ejemplo n.º 44
0
    def walk_debug(self, formula, **kwargs):
        from pysmt.shortcuts import Equals, Iff, get_type, is_valid
        from pysmt.typing import BOOL

        if formula in self.memoization:
            return self.memoization[formula]

        args = [self.walk(s, **kwargs) for s in formula.get_sons()]

        f = self.functions[formula.node_type()]
        res = f(formula, args, **kwargs)
        ltype = get_type(formula)
        rtype = get_type(res)
        test = Equals(formula, res) if ltype != BOOL else Iff(formula, res)
        assert (ltype == rtype) and is_valid(test, solver_name="z3"), \
               ("Was: %s \n Obtained: %s\n" % (str(formula), str(res)))
        return res
Ejemplo n.º 45
0
    def walk_debug(self, formula, **kwargs):
        from pysmt.shortcuts import Equals, Iff, get_type, is_valid
        from pysmt.typing import BOOL

        if formula in self.memoization:
            return self.memoization[formula]

        args = [self.walk(s, **kwargs) for s in formula.args()]

        f = self.functions[formula.node_type()]
        res = f(formula, args=args, **kwargs)
        ltype = get_type(formula)
        rtype = get_type(res)
        test = Equals(formula, res) if ltype != BOOL else Iff(formula, res)
        assert (ltype == rtype) and is_valid(test, solver_name="z3"), \
               ("Was: %s \n Obtained: %s\n" % (str(formula), str(res)))
        return res
Ejemplo n.º 46
0
 def test_examples(self):
     for name in self.all_solvers:
         for example in get_example_formulae():
             f = example.expr
             try:
                 v = is_valid(f, solver_name=name)
                 s = is_sat(f, solver_name=name)
                 self.assertEqual(example.is_valid, v, f)
                 self.assertEqual(example.is_sat, s, f)
             except NoSolverAvailableError:
                 # The solver does not support the specified logic
                 continue
             except UnknownSolverAnswerError:
                 # MathSAT does not deal with UF with boolean args.
                 # This is handled via the native API, but not via the
                 # SMT-LIB Wrapper
                 self.assertTrue(name == "mathsat.solver.sh", name)
Ejemplo n.º 47
0
    def test_simplify_qf_hard(self):
        """Test simplifier on random formula.

        This version of the test forces the simplifier to validate
        each simplification step, therefore it is slow, and we run it
        only on few sample formulas.
        """
        for i in xrange(FEW_ITERATIONS):
            f = build_random_qf_formula(10, 20, 5, 0.1, seed=i)
            get_env().simplifier.validate_simplifications = True
            sf = f.simplify()
            get_env().simplifier.validate_simplifications = False

            res = is_valid(Iff(f, sf), solver_name='z3')
            self.assertTrue(
                res, "Simplification did not provide equivalent " +
                "result:\n f= %s\n sf = %s" % (f, sf))
Ejemplo n.º 48
0
 def test_examples(self):
     for name in self.all_solvers:
         for example in get_example_formulae():
             f = example.expr
             try:
                 v = is_valid(f, solver_name=name)
                 s = is_sat(f, solver_name=name)
                 self.assertEqual(example.is_valid, v, f)
                 self.assertEqual(example.is_sat, s, f)
             except NoSolverAvailableError:
                 # The solver does not support the specified logic
                 continue
             except UnknownSolverAnswerError:
                 # MathSAT does not deal with UF with boolean args.
                 # This is handled via the native API, but not via the
                 # SMT-LIB Wrapper
                 self.assertTrue(name == "mathsat.solver.sh", name)
Ejemplo n.º 49
0
    def test_msat_back_simple(self):
        from pysmt.solvers.msat import MathSAT5Solver, MSatConverter

        env = get_env()
        msat = MathSAT5Solver(environment=env, logic=QF_UFLIRA)
        new_converter = MSatConverter(env, msat.msat_env)

        r, s = FreshSymbol(REAL), FreshSymbol(INT)
        f1 = GT(r, Real(1))
        f2 = LE(Plus(s, Int(2)), Int(3))
        f3 = LE(Int(2), Int(3))
        f = And(f1, f2, f3)

        term = new_converter.convert(f)
        res = new_converter.back(term)

        # Checking equality is not enough: MathSAT can change the
        # shape of the formula into a logically equivalent form.
        self.assertTrue(is_valid(Iff(f, res), logic=QF_UFLIRA))
Ejemplo n.º 50
0
    def test_tactics_z3(self):
        from z3 import Tactic, Then
        from pysmt.shortcuts import Iff

        my_tactic = Then(Tactic('simplify'), Tactic('propagate-values'),
                         Tactic('elim-uncnstr'))

        for (f, validity, satisfiability, logic) in get_example_formulae():
            if not logic.theory.linear: continue
            if not logic.quantifier_free: continue
            if logic.theory.bit_vectors: continue
            s = Solver(name='z3')
            z3_f = s.converter.convert(f)
            simp_z3_f = my_tactic(z3_f)
            simp_f = s.converter.back(simp_z3_f.as_expr())
            v = is_valid(simp_f)
            s = is_sat(simp_f)
            self.assertEqual(v, validity, (f, simp_f))
            self.assertEqual(s, satisfiability, (f, simp_f))
Ejemplo n.º 51
0
    def test_tactics_z3(self):
        from z3 import Tactic, Then
        from pysmt.shortcuts import Iff

        my_tactic = Then(Tactic('simplify'), Tactic('propagate-values'),
                         Tactic('elim-uncnstr'))

        for (f, validity, satisfiability, logic) in get_example_formulae():
            if not logic.theory.linear: continue
            if not logic.quantifier_free: continue
            if logic.theory.bit_vectors: continue
            s = Solver(name='z3')
            z3_f = s.converter.convert(f)
            simp_z3_f = my_tactic(z3_f)
            simp_f = s.converter.back(simp_z3_f.as_expr())
            v = is_valid(simp_f)
            s = is_sat(simp_f)
            self.assertEqual(v, validity, (f, simp_f))
            self.assertEqual(s, satisfiability, (f, simp_f))
Ejemplo n.º 52
0
# Verify the correctness of a rewriting using Bit-Vectors
#
# The following expression computes the xor of y and x:
#  (((y & x)*-2) + (y + x)
#
# We verify that this is indeed the case
#
# Source: https://yurichev.com/writings/SAT_SMT_draft-EN.pdf
#
from pysmt.shortcuts import SBV, Symbol, is_valid, Equals
from pysmt.typing import BV16

# X and Y are BV of width 16
x = Symbol("x", BV16)
y = Symbol("y", BV16)

r1 = y + x            # add   r1,ry,rx
r2 = y & x            # and   r2,ry,rx
r3 = r2 * SBV(-2, 16) # mul   r3,r2,-2
r4 = r3 + r1          # add   r4,r3,r1

# x xor y == r4
real_xor = x ^ y
assert is_valid(real_xor.Equals(r4))
Ejemplo n.º 53
0
def safeRL_callSMT(action, start_pos_x, start_pos_y, dynamical_parameters,
                   image, bird_param):

    flapup_paths = None
    godown_paths = None
    smt_result = 0
    path_depth = 8
    if (action == 1):
        #==========================================================================================================
        # properties for safe flap up action
        #----------------------------------------------------------------------------------------------------------
        #property 1: safe_upper_height is the safe max altitude of the bird, depending upon the game
        safe_max_height = 70
        safety_prop_1 = GE(Int(dynamical_parameters['pos_y']),
                           Int(safe_max_height))

        #property 2:if there is no escape path if it takes action flap, then do not take it.
        # number_of_ states to check for safe movement depends upon the game speed, bird vel etc.
        path_list = []

        temp_dynamical_parameters = {}
        temp_dynamical_parameters['pos_x'], temp_dynamical_parameters[
            'pos_y'], temp_dynamical_parameters['vel_y'] = predict_next_steps(
                dynamical_parameters['pos_x'], dynamical_parameters['pos_y'],
                dynamical_parameters['vel_y'], action, dynamical_parameters)
        path = [(temp_dynamical_parameters['pos_x'],
                 temp_dynamical_parameters['pos_y'])]
        action_ctr = 1
        flapup_paths = recursive_path_generator(
            temp_dynamical_parameters['pos_x'],
            temp_dynamical_parameters['pos_y'],
            temp_dynamical_parameters['vel_y'],
            action_ctr,
            dynamical_parameters,
            path_list,
            path_depth,
            path=path)
        is_flap_up_path_clear = is_path_safe(image, flapup_paths,
                                             bird_param['w'], bird_param['h'],
                                             action)
        safety_prop_2 = (Bool(is_flap_up_path_clear))
        #----------------------------------------------------------------------------------------------------------

        #property 3: Safe vertical distance of bird from pipe - when it goes through the pipe
        # min distance between pipe and bird.
        safe_v_pipe_dist = 15
        bird_epsilon = 10
        is_upper_pipe_far = is_safe_from_upper_pipe(
            image, start_pos_x, start_pos_y, (bird_param['w'] + bird_epsilon),
            (bird_param['h'] + bird_epsilon), safe_v_pipe_dist)
        safety_prop_3 = (Bool(is_upper_pipe_far))
        #----------------------------------------------------------------------------------------------------------

        #print(" Before smt  ", datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3])
        properties_for_flap_action = And(safety_prop_1, safety_prop_2,
                                         safety_prop_3)
        res = is_valid(properties_for_flap_action, solver_name="z3")
        #print("flap  :", properties_for_flap_action, "      " , res)
        if res:
            smt_result = 1

    if (action == 0):
        #----------------------------------------------------------------------------------------------------------
        # properties for safe no action
        #----------------------------------------------------------------------------------------------------------
        #property : safe_min_height is the min altitude of the bird
        #safe_min_height value depends on the game. Its hardcoded to 500 for this game.
        safe_min_height = 300
        safety_prop_10 = LE(Int(dynamical_parameters['pos_y']),
                            Int(safe_min_height))

        #property :if there is no escape path if it takes action no flap, then do not take it.
        # number_of_ states to check for safe movement depends upon the game speed, bird vel etc.
        #next_possible_actions = down_action_sequence_for_path(path_depth)
        #godown_paths = path_generator (start_pos_x, start_pos_y + 20,dynamical_parameters,  next_possible_actions)

        path_list = []
        temp_dynamical_parameters = {}
        temp_dynamical_parameters['pos_x'], temp_dynamical_parameters[
            'pos_y'], temp_dynamical_parameters['vel_y'] = predict_next_steps(
                dynamical_parameters['pos_x'], dynamical_parameters['pos_y'],
                dynamical_parameters['vel_y'], action, dynamical_parameters)
        path = [(temp_dynamical_parameters['pos_x'],
                 temp_dynamical_parameters['pos_y'])]
        action_ctr = 1
        godown_paths = recursive_path_generator(
            temp_dynamical_parameters['pos_x'],
            temp_dynamical_parameters['pos_y'],
            temp_dynamical_parameters['vel_y'],
            action_ctr,
            dynamical_parameters,
            path_list,
            path_depth,
            path=path)
        #print(" godown_paths  : ", godown_paths)
        is_go_down_clear = is_path_safe(image, godown_paths, bird_param['w'],
                                        bird_param['h'], action)
        safety_prop_11 = (Bool(is_go_down_clear))
        #----------------------------------------------------------------------------------------------------------

        #property 3: Safe vertical distance of bird from pipe - when it goes through the pipe
        # min distance between pipe and bird.
        safe_v_pipe_dist = 15
        bird_epsilon = 10
        is_lower_pipe_far = is_safe_from_lower_pipe(
            image, start_pos_x, start_pos_y, (bird_param['w'] + bird_epsilon),
            (bird_param['h'] + bird_epsilon), safe_v_pipe_dist)
        safety_prop_12 = (Bool(is_lower_pipe_far))
        #----------------------------------------------------------------------------------------------------------

        properties_for_no_action = And(safety_prop_10, safety_prop_11,
                                       safety_prop_12)
        res = is_valid(properties_for_no_action, solver_name="z3")
        #print("down  :", properties_for_no_action, "      " , res)
        if res:
            smt_result = 2

    return smt_result, flapup_paths, godown_paths
Ejemplo n.º 54
0
    def test_bv(self):
        mgr = self.env.formula_manager
        BV = mgr.BV

        # Constants
        one = BV(1, 32)
        zero = BV(0, 32)
        big = BV(127, 128)
        binary = BV("111")
        binary2 = BV("#b111")
        binary3 = BV(0b111, 3) # In this case we need to explicit the width

        self.assertEqual(binary, binary2)
        self.assertEqual(binary2, binary3)
        self.assertEqual(one, mgr.BVOne(32))
        self.assertEqual(zero, mgr.BVZero(32))

        # Type Equality
        self.assertTrue(BV32 != BV128)
        self.assertFalse(BV32 != BV32)
        self.assertFalse(BV32 == BV128)
        self.assertTrue(BV32 == BV32)

        with self.assertRaises(PysmtValueError):
            # Negative numbers are not supported
            BV(-1, 10)
        with self.assertRaises(PysmtValueError):
            # Number should fit in the width
            BV(10, 2)

        # Variables
        b128 = Symbol("b", BV128) # BV1, BV8 etc. are defined in pysmt.typing
        b32 = Symbol("b32", BV32)
        hexample = BV(0x10, 32)
        bcustom = Symbol("bc", BVType(42))

        self.assertIsNotNone(hexample)
        self.assertIsNotNone(bcustom)
        self.assertEqual(bcustom.bv_width(), 42)
        self.assertEqual(hexample.constant_value(), 16)

        not_zero32 = mgr.BVNot(zero)
        not_b128 = mgr.BVNot(b128)
        self.assertTrue(not_b128.is_bv_not())

        f1 = Equals(not_zero32, b32)
        f2 = Equals(not_b128, big)
        self.assertTrue(is_sat(f1, logic=QF_BV))
        self.assertTrue(is_sat(f2, logic=QF_BV))

        zero_and_one = mgr.BVAnd(zero, one)
        self.assertTrue(zero_and_one.is_bv_and())
        zero_or_one = mgr.BVOr(zero, one)
        self.assertTrue(zero_or_one.is_bv_or())
        zero_xor_one = mgr.BVXor(zero, one)
        self.assertTrue(zero_xor_one.is_bv_xor())

        zero_xor_one.simplify()
        self.assertTrue(zero_xor_one.is_bv_op())

        f1 = Equals(zero_and_one, b32)
        f2 = Equals(zero_or_one, b32)
        f3 = Equals(zero_xor_one, b32)
        f4 = Equals(zero_xor_one, one)

        self.assertTrue(is_sat(f1, logic=QF_BV), f1)
        self.assertTrue(is_sat(f2, logic=QF_BV), f2)
        self.assertTrue(is_sat(f3, logic=QF_BV), f3)
        self.assertTrue(is_valid(f4, logic=QF_BV), f4)

        with self.assertRaises(PysmtTypeError):
            mgr.BVAnd(b128, zero)

        f = mgr.BVAnd(b32, zero)
        f = mgr.BVOr(f, b32)
        f = mgr.BVXor(f, b32)
        f = Equals(f, zero)

        self.assertTrue(is_sat(f, logic=QF_BV), f)

        zero_one_64 = mgr.BVConcat(zero, one)
        one_zero_64 = mgr.BVConcat(one, zero)
        one_one_64  = mgr.BVConcat(one, one)
        self.assertTrue(one_one_64.is_bv_concat())
        self.assertFalse(one_one_64.is_bv_and())

        self.assertTrue(zero_one_64.bv_width() == 64)
        f1 = Equals(mgr.BVXor(one_zero_64, zero_one_64),
                    one_one_64)

        self.assertTrue(is_sat(f1, logic=QF_BV), f1)

        # MG: BV indexes grow to the left.
        # This is confusing and we should address this.
        extraction = mgr.BVExtract(zero_one_64, 32, 63)
        self.assertTrue(is_valid(Equals(extraction, zero)))

        ult = mgr.BVULT(zero, one)
        self.assertTrue(ult.is_bv_ult())
        neg = mgr.BVNeg(one)
        self.assertTrue(neg.is_bv_neg())
        self.assertTrue(is_valid(ult, logic=QF_BV), ult)
        test_eq = Equals(neg, one)
        self.assertTrue(is_unsat(test_eq, logic=QF_BV))

        f = zero
        addition = mgr.BVAdd(f, one)
        self.assertTrue(addition.is_bv_add())
        multiplication = mgr.BVMul(f, one)
        self.assertTrue(multiplication.is_bv_mul())
        udiv = mgr.BVUDiv(f, one)
        self.assertTrue(udiv.is_bv_udiv())

        self.assertTrue(is_valid(Equals(addition, one), logic=QF_BV), addition)
        self.assertTrue(is_valid(Equals(multiplication, zero), logic=QF_BV), multiplication)
        self.assertTrue(is_valid(Equals(udiv, zero), logic=QF_BV), udiv)

        three = mgr.BV(3, 32)
        two = mgr.BV(2, 32)
        self.assertEqual(3, three.bv2nat())

        reminder = mgr.BVURem(three, two)
        self.assertTrue(reminder.is_bv_urem())
        shift_l_a = mgr.BVLShl(one, one)
        self.assertTrue(shift_l_a.is_bv_lshl())
        shift_l_b = mgr.BVLShl(one, 1)

        self.assertTrue(is_valid(Equals(reminder, one)), reminder)
        self.assertEqual(shift_l_a, shift_l_b)
        self.assertTrue(is_valid(Equals(shift_l_a, two)))

        shift_r_a = mgr.BVLShr(one, one)
        self.assertTrue(shift_r_a.is_bv_lshr())
        shift_r_b = mgr.BVLShr(one, 1)
        self.assertEqual(shift_r_a, shift_r_b)
        self.assertTrue(is_valid(Equals(shift_r_a, zero)))

        ashift_r_a = mgr.BVAShr(one, one)
        ashift_r_b = mgr.BVAShr(one, 1)
        self.assertEqual(ashift_r_a, ashift_r_b)
        self.assertTrue(ashift_r_a.is_bv_ashr())

        rotate_l = mgr.BVRol(one, 3)
        self.assertTrue(rotate_l.is_bv_rol())
        rotate_r = mgr.BVRor(rotate_l, 3)
        self.assertTrue(rotate_r.is_bv_ror())
        self.assertTrue(is_valid(Equals(one, rotate_r)))

        zero_ext = mgr.BVZExt(one, 64)
        self.assertTrue(zero_ext.is_bv_zext())
        signed_ext = mgr.BVSExt(one, 64)
        self.assertTrue(signed_ext.is_bv_sext())
        signed_ext2 = mgr.BVSExt(mgr.BVNeg(one), 64)

        self.assertNotEqual(signed_ext2, signed_ext)
        self.assertTrue(is_valid(Equals(zero_ext, signed_ext), logic=QF_BV))

        x = Symbol("x")
        g = And(x, mgr.BVULT(zero, one))

        res = is_sat(g, logic=QF_BV)
        self.assertTrue(res)

        model = get_model(g, logic=QF_BV)
        self.assertTrue(model[x] == TRUE())

        gt_1 = mgr.BVUGT(zero, one)
        gt_2 = mgr.BVULT(one, zero)
        self.assertEqual(gt_1, gt_2)

        gte_1 = mgr.BVULE(zero, one)
        gte_2 = mgr.BVUGE(one, zero)
        self.assertEqual(gte_1, gte_2)

        self.assertTrue(is_valid(gte_2, logic=QF_BV))

        ide = Equals(mgr.BVNeg(BV(10, 32)), mgr.SBV(-10, 32))
        self.assertValid(ide, logic=QF_BV)

        # These should work without exceptions
        mgr.SBV(-2, 2)
        mgr.SBV(-1, 2)
        mgr.SBV(0, 2)
        mgr.SBV(1, 2)

        # Overflow and Underflow
        with self.assertRaises(PysmtValueError):
            mgr.SBV(2, 2)
        with self.assertRaises(PysmtValueError):
            mgr.SBV(-3, 2)

        # These should work without exceptions
        mgr.BV(0, 2)
        mgr.BV(1, 2)
        mgr.BV(2, 2)
        mgr.BV(3, 2)
        # Overflow
        with self.assertRaises(PysmtValueError):
            mgr.BV(4, 2)
        # No negative number allowed
        with self.assertRaises(PysmtValueError):
            mgr.BV(-1, 2)

        # SBV should behave as BV for positive numbers
        self.assertEqual(mgr.SBV(10, 16), mgr.BV(10, 16))

        # Additional is_bv_* tests
        f = mgr.BVSub(one, one)
        self.assertTrue(f.is_bv_sub())

        f = mgr.BVSLT(one, one)
        self.assertTrue(f.is_bv_slt())
        f = mgr.BVSLE(one, one)
        self.assertTrue(f.is_bv_sle())
        f = mgr.BVComp(one, one)
        self.assertTrue(f.is_bv_comp())
        f = mgr.BVSDiv(one, one)
        self.assertTrue(f.is_bv_sdiv())
        f = mgr.BVSRem(one, one)
        self.assertTrue(f.is_bv_srem())
        f = mgr.BVULE(one, one)
        self.assertTrue(f.is_bv_ule())
Ejemplo n.º 55
0
def check_validity_and_test(args):
    """Checks expression and compare the outcome against a known value."""

    expr, expected = args # IMPORTANT: Unpack args !!!
    local_res = is_valid(expr)
    return local_res == expected