Exemple #1
0
def main():
    em = ExprManager()
    smt = SmtEngine(em)

    # Prove that for integers x and y:
    #   x > 0 AND y > 0  =>  2x + y >= 3

    integer = em.integerType()

    x = em.mkVar("x", integer)
    y = em.mkVar("y", integer)
    zero = em.mkConst(Rational(0))

    x_positive = em.mkExpr(CVC4.GT, x, zero)
    y_positive = em.mkExpr(CVC4.GT, y, zero)

    two = em.mkConst(Rational(2))
    twox = em.mkExpr(CVC4.MULT, two, x)
    twox_plus_y = em.mkExpr(CVC4.PLUS, twox, y)

    three = em.mkConst(Rational(3))
    twox_plus_y_geq_3 = em.mkExpr(CVC4.GEQ, twox_plus_y, three)

    formula = Expr(em.mkExpr(CVC4.AND, x_positive,
                             y_positive)).impExpr(Expr(twox_plus_y_geq_3))

    print "Checking validity of formula " + formula.toString() + " with CVC4."
    print "CVC4 should report VALID."
    print "Result from CVC4 is: " + smt.query(formula).toString()

    return 0
Exemple #2
0
def main():
  em = ExprManager()
  smt = SmtEngine(em)

  # Prove that for integers x and y:
  #   x > 0 AND y > 0  =>  2x + y >= 3

  integer = em.integerType()

  x = em.mkVar("x", integer)
  y = em.mkVar("y", integer)
  zero = em.mkConst(Rational(0))

  x_positive = em.mkExpr(CVC4.GT, x, zero)
  y_positive = em.mkExpr(CVC4.GT, y, zero)

  two = em.mkConst(Rational(2))
  twox = em.mkExpr(CVC4.MULT, two, x)
  twox_plus_y = em.mkExpr(CVC4.PLUS, twox, y)

  three = em.mkConst(Rational(3))
  twox_plus_y_geq_3 = em.mkExpr(CVC4.GEQ, twox_plus_y, three)

  formula = Expr(em.mkExpr(CVC4.AND, x_positive, y_positive)).impExpr(Expr(twox_plus_y_geq_3))

  print "Checking validity of formula " + formula.toString() + " with CVC4."
  print "CVC4 should report VALID."
  print "Result from CVC4 is: " + smt.query(formula).toString()

  return 0
Exemple #3
0
 def findCounterexample(self, asserts, query, timeout=None):
     """Tries to find a counterexample to the query while
        asserts remains valid."""
     self.em = ExprManager()
     self.solver = SmtEngine(self.em)
     if timeout is not None:
         self.options['tlimit-per'] = timeout * 1000
     for name, value in CVCWrapper.options.items():
         self.solver.setOption(name, SExpr(str(value)))
     self.solver.setLogic(CVCWrapper.logic)
     self.query = query
     self.asserts = asserts
     result, model = self._findModel()
     return result, model
Exemple #4
0
 def findCounterexample(self, asserts, query):
     """Tries to find a counterexample to the query while
        asserts remains valid."""
     self.em = ExprManager()
     self.solver = SmtEngine(self.em)
     for name, value in CVCWrapper.options.items():
         self.solver.setOption(name, SExpr(str(value)))
     self.solver.setLogic(CVCWrapper.logic)
     self.query = query
     self.asserts = self._coneOfInfluence(asserts, query)
     result = self._findModel()
     log.debug("Query -- %s" % self.query)
     log.debug("Asserts -- %s" % asserts)
     log.debug("Cone -- %s" % self.asserts)
     log.debug("Result -- %s" % result)
     return result
Exemple #5
0
 def findCounterexample(self, asserts, query, timeout=10**10):
     starttime = time.process_time()
     Z3Str2Wrapper.options['tlimit-per'] = timeout * 1000
     self.solvetimeout = timeout
     self.em = ExprManager()
     self.solver = SmtEngine(self.em)
     for name, value in Z3Str2Wrapper.options.items():
         self.solver.setOption(name, SExpr(str(value)))
     self.solver.setLogic(Z3Str2Wrapper.logic)
     self.query = query
     self.asserts = asserts
     result, model = self._findModel()
     endtime = time.process_time()
     log.debug("Timeout -- %s" % timeout)
     log.debug("Result -- %s" % result)
     log.debug("Model -- %s" % model)
     log.debug("Solver time: {0:.2f} seconds".format(timeout))
     solvertime = endtime - starttime
     return result, model, solvertime
Exemple #6
0
 def findCounterexample(self, asserts, query, timeout=None):
     """Tries to find a counterexample to the query while
        asserts remains valid."""
     startime = time.process_time()
     self.em = ExprManager()
     self.solver = SmtEngine(self.em)
     if timeout is not None:
         self.options['tlimit-per'] = timeout * 1000
     for name, value in CVCWrapper.options.items():
         self.solver.setOption(name, SExpr(str(value)))
     self.solver.setLogic(CVCWrapper.logic)
     self.query = query
     self.asserts = asserts
     result, model = self._findModel()
     endtime = time.process_time()
     log.debug("Timeout -- %s" % timeout)
     log.debug("Result -- %s" % result)
     log.debug("Model -- %s" % model)
     log.debug("Solver time: {0:.2f} seconds".format(endtime - startime))
     solvertime = endtime - startime
     return result, model, solvertime
Exemple #7
0
def check_covered(dim, set1, list_of_covers):
    em = ExprManager()
    s_cover = SmtEngine(em)
    real_type = em.realType()

    x = [em.mkVar("x_[%s]" % (j + 1), real_type) for j in range(dim)]
    list_of_constraints = []

    #x \in set1
    list_of_constraints.append(get_point_membership_constraint(em, x, set1))

    #x is not in any of the covers
    for cover in list_of_covers:
        list_of_constraints.append(
            em.mkExpr(CVC4.NOT, get_point_membership_constraint(em, x, cover)))

    s_cover.assertFormula(get_cvc4_and(em, list_of_constraints))
    chk = s_cover.checkSat()
    if (chk == 1):
        return False
    else:
        return True
Exemple #8
0
 def findCounterexample(self, asserts, query):
     """Tries to find a counterexample to the query while
        asserts remains valid."""
     self.em = ExprManager()
     self.solver = SmtEngine(self.em)
     for name, value in CVCWrapper.options.items():
         self.solver.setOption(name, SExpr(str(value)))
     self.solver.setLogic(CVCWrapper.logic)
     self.query = query
     self.asserts = self._coneOfInfluence(asserts, query)
     result = self._findModel()
     log.debug("Query -- %s" % self.query)
     log.debug("Asserts -- %s" % asserts)
     log.debug("Cone -- %s" % self.asserts)
     log.debug("Result -- %s" % result)
     return result
Exemple #9
0
 def findCounterexample(self, asserts, query):
     """Tries to find a counterexample to the query while
        asserts remains valid."""
     self.em = ExprManager()
     self.solver = SmtEngine(self.em)
     self.solver.setOption("produce-models", SExpr("true"))
     self.solver.setOption("strings-exp", SExpr("true")) # Enable experimental string support
     self.solver.setOption("rewrite-divk", SExpr("true")) # Enable modular arithmetic with constant modulus
     self.solver.setOption("tlimit-per", SExpr("5000")) # Per Query timeout of 5 seconds
     self.solver.setLogic("ALL_SUPPORTED")
     self.query = query
     self.asserts = self._coneOfInfluence(asserts, query)
     result = self._findModel()
     log.debug("Query -- %s" % self.query)
     log.debug("Asserts -- %s" % asserts)
     log.debug("Cone -- %s" % self.asserts)
     log.debug("Result -- %s" % result)
     return result
Exemple #10
0
 def findCounterexample(self, asserts, query, timeout=None):
     """Tries to find a counterexample to the query while
        asserts remains valid."""
     startime = time.process_time()
     self.em = ExprManager()
     self.solver = SmtEngine(self.em)
     if timeout is not None:
         self.options['tlimit-per'] = timeout*1000
     for name, value in CVCWrapper.options.items():
         self.solver.setOption(name, SExpr(str(value)))
     self.solver.setLogic(CVCWrapper.logic)
     self.query = query
     self.asserts = asserts
     result, model = self._findModel()
     endtime = time.process_time()
     log.debug("Timeout -- %s" % timeout)
     log.debug("Result -- %s" % result)
     log.debug("Model -- %s" % model)
     log.debug("Solver time: {0:.2f} seconds".format(endtime - startime))
     solvertime = endtime - startime
     return result, model, solvertime
Exemple #11
0
class CVCWrapper(object):
    options = {
        'produce-models': 'true',
        # Enable experimental string support
        'strings-exp': 'true',
        # Enable modular arithmetic with constant modulus
        'rewrite-divk': 'true',
        'output-language': 'smt2',
        'input-language': 'smt2'
    }
    logic = 'ALL_SUPPORTED'

    def __init__(self, query_store=None):
        self.asserts = None
        self.query = None
        self.em = None
        self.solver = None
        self.query_store = query_store
        self.smtlib = None

    def findCounterexample(self, asserts, query, timeout=None):
        """Tries to find a counterexample to the query while
           asserts remains valid."""
        startime = time.process_time()
        self.em = ExprManager()
        self.solver = SmtEngine(self.em)
        if timeout is not None:
            self.options['tlimit-per'] = timeout * 1000
        for name, value in CVCWrapper.options.items():
            self.solver.setOption(name, SExpr(str(value)))
        self.solver.setLogic(CVCWrapper.logic)
        self.query = query
        self.asserts = asserts
        result, model = self._findModel()
        endtime = time.process_time()
        log.debug("Timeout -- %s" % timeout)
        log.debug("Result -- %s" % result)
        log.debug("Model -- %s" % model)
        log.debug("Solver time: {0:.2f} seconds".format(endtime - startime))
        solvertime = endtime - startime
        return result, model, solvertime

    def _findModel(self):
        self.solver.push()
        exprbuilder = ExprBuilder(self.asserts, self.query, self.solver)
        self.solver.assertFormula(exprbuilder.query.cvc_expr)
        if self.query_store is not None:
            self.smtlib = self._serialize(exprbuilder.query,
                                          exprbuilder.cvc_vars)
            self._savequery()
        model = None
        try:
            result = self.solver.checkSat()
            if not result.isSat():
                ret = "UNSAT"
            elif result.isUnknown():
                ret = "UNKNOWN"
            elif result.isSat():
                ret = "SAT"
                model = self._getModel(exprbuilder.cvc_vars)
            else:
                raise Exception("Unexpected SMT result")
        except RuntimeError as r:
            log.debug("CVC exception %s" % r)
            ret = "UNKNOWN"
        except TypeError as t:
            log.error("CVC exception %s" % t)
            ret = "UNKNOWN"
        self.solver.pop()
        return ret, model

    def _savequery(self):
        if not path.isdir(self.query_store):
            raise IOError("Query folder {} not found".format(self.query_store))
        smthash = sha224(bytes(str(self.query), 'UTF-8')).hexdigest()
        filename = path.join(self.query_store, "{}.smt2".format(smthash))
        log.debug('Writing query to {}'.format(filename))
        with open(filename, 'w') as f:
            f.write(self.smtlib)

    @staticmethod
    def _serialize(query, variables):
        smtlib_template = Template("""
(set-logic $logic)
(set-option :strings-exp ${strings_exp})
(set-option :produce-models ${produce_models})
(set-option :rewrite-divk ${rewrite_divk})

$declarevars

(assert $query)

(check-sat)

$getvars
""")
        assignments = {
            name.replace('-', '_'): value
            for name, value in CVCWrapper.options.items()
        }
        assignments['logic'] = CVCWrapper.logic
        assignments['query'] = query
        assignments['declarevars'] = "\n".join(
            "(declare-fun {} () {})".format(name, var.CVC_TYPE)
            for name, var in variables.items())
        assignments['getvars'] = "\n".join("(get-value ({}))".format(name)
                                           for name in variables)
        return smtlib_template.substitute(assignments).strip()

    @staticmethod
    def _getModel(variables):
        """Retrieve the model generated for the path expression."""
        return {
            name: cvc_var.getvalue()
            for (name, cvc_var) in variables.items()
        }
Exemple #12
0
class CVCWrapper(object):
    options = {
        'produce-models': 'true',
        # Enable experimental string support
        'strings-exp': 'true',
        # Enable modular arithmetic with constant modulus
        'rewrite-divk': 'true',
        'output-language': 'smt2',
        'input-language': 'smt2'
    }
    logic = 'ALL_SUPPORTED'

    def __init__(self):
        self.asserts = None
        self.query = None
        self.em = None
        self.solver = None
        self.smtlib = None

    def findCounterexample(self, asserts, query, timeout=None):
        """Tries to find a counterexample to the query while
           asserts remains valid."""
        self.em = ExprManager()
        self.solver = SmtEngine(self.em)
        if timeout is not None:
            self.options['tlimit-per'] = timeout * 1000
        for name, value in CVCWrapper.options.items():
            self.solver.setOption(name, SExpr(str(value)))
        self.solver.setLogic(CVCWrapper.logic)
        self.query = query
        self.asserts = asserts
        result, model = self._findModel()
        return result, model

    def _findModel(self):
        self.solver.push()
        exprbuilder = ExprBuilder(self.asserts, self.query, self.solver)
        print("FORMULA: (assert " + exprbuilder.query.cvc_expr.toString() +
              " )")
        self.solver.assertFormula(exprbuilder.query.cvc_expr)
        model = None
        try:
            result = self.solver.checkSat()
            if not result.isSat():
                ret = "UNSAT"
            elif result.isUnknown():
                ret = "UNKNOWN"
            elif result.isSat():
                ret = "SAT"
                model = self._getModel(exprbuilder.cvc_vars)
            else:
                raise Exception("Unexpected SMT result")
        except RuntimeError as r:
            print("CVC exception %s" % r)
            ret = "UNKNOWN"
        except TypeError as t:
            print("CVC exception %s" % t)
            ret = "UNKNOWN"
        self.solver.pop()

        return ret, model

    @staticmethod
    def _getModel(variables):
        """Retrieve the model generated for the path expression."""
        return {
            name: cvc_var.getvalue()
            for (name, cvc_var) in variables.items()
        }
Exemple #13
0
class Z3Str2Wrapper(object):
    options = {
        'produce-models': 'true',
        # Enable experimental string support
        'strings-exp': 'true',
        # Enable modular arithmetic with constant modulus
        'rewrite-divk': 'true',
        # Per Query timeout of 30 seconds
        'tlimit-per': 30000,
        'output-language': 'smt2',
        'input-language': 'smt2'
    }
    rename = {
        'str.len': 'Length',
        'str.contains': 'Contains',
        'str.indexof': 'Indexof2',
        'str.substr': 'Substring',
        'str.++': 'Concat',
        'str.replace': 'Replace',
        'str.at': 'CharAt',
        'bv2nat': 'bv2int'
    }
    logic = 'ALL_SUPPORTED'

    def __init__(self, query_store=None):
        if query_store is None:
            self.query_store = mkdtemp()
        else:
            self.query_store = query_store
        self.solvertime = 0

    def findCounterexample(self, asserts, query, timeout=10**10):
        starttime = time.process_time()
        Z3Str2Wrapper.options['tlimit-per'] = timeout * 1000
        self.solvetimeout = timeout
        self.em = ExprManager()
        self.solver = SmtEngine(self.em)
        for name, value in Z3Str2Wrapper.options.items():
            self.solver.setOption(name, SExpr(str(value)))
        self.solver.setLogic(Z3Str2Wrapper.logic)
        self.query = query
        self.asserts = asserts
        result, model = self._findModel()
        endtime = time.process_time()
        log.debug("Timeout -- %s" % timeout)
        log.debug("Result -- %s" % result)
        log.debug("Model -- %s" % model)
        log.debug("Solver time: {0:.2f} seconds".format(timeout))
        solvertime = endtime - starttime
        return result, model, solvertime

    def _findModel(self):
        self.solver.push()
        exprbuilder = ExprBuilder(self.asserts, self.query, self.solver)
        self.solver.assertFormula(exprbuilder.query.cvc_expr)
        smtlib = CVCWrapper._serialize(exprbuilder.query, exprbuilder.cvc_vars)
        transformed_smtlib = [
            self._transform(s) for s in sexpdata.parse(smtlib)
        ]
        z3str2 = ""
        for line in transformed_smtlib:
            z3str2 += sexpdata.dumps(line, none_as='').strip().replace(
                '\\\\', '\\') + "\n"
        rawoutput = None
        with NamedTemporaryFile(mode='w', suffix=".smt2") as f:
            f.write(z3str2)
            f.flush()
            startime = time.clock()
            try:
                rawoutput = str(
                    check_output([
                        "timeout",
                        str(self.solvetimeout), "z3-str", "-f", f.name
                    ],
                                 universal_newlines=True))
            except CalledProcessError as e:
                if e.returncode == 124:
                    return "UNKNOWN", None
            endtime = time.clock()
            log.debug("Solver time: {0:.2f} seconds".format(endtime -
                                                            startime))
            self.solvertime += endtime - startime
        if ">> SAT" not in rawoutput:
            return "UNSAT", None
        model = {}
        for name in exprbuilder.cvc_vars:
            patterns = {
                "{} : int -> (-?\d+)": int,
                "{} : string -> \"([\S \\\\]*)\"": str
            }
            for pattern, constructor in patterns.items():
                match = re.search(pattern.format(name), rawoutput)
                if match is not None:
                    if constructor == str:
                        model[name] = bytes(constructor(match.group(1)),
                                            "utf-8").decode("unicode_escape")
                    else:
                        model[name] = constructor(match.group(1))
        return "SAT", model

    def _transform(self, smtlib):
        if isinstance(smtlib, Symbol) or isinstance(smtlib, int):
            return smtlib
        elif isinstance(smtlib, str):
            smtlib = smtlib.replace('\\', '\\\\')
            smtlib = smtlib.replace('\\\\v', '\\v')
            smtlib = smtlib.replace('\\\\x', '\\x')
            return smtlib
        if isinstance(smtlib[0], list):
            return [self._transform(subsmtlib) for subsmtlib in smtlib]
        stmtname = smtlib[0].value()
        if stmtname in ('set-logic', 'set-option'):
            return None
        elif stmtname == 'get-value':
            return Symbol('get-model'),
        elif stmtname == 'declare-fun':
            declare, name, func, smttype = smtlib
            return Symbol('declare-variable'), name, smttype
        elif stmtname == 'str.prefixof':
            stmtname, prefix, string = smtlib
            return Symbol('StartsWith'), self._transform(
                string), self._transform(prefix)
        elif stmtname in Z3Str2Wrapper.rename:
            return [Symbol(Z3Str2Wrapper.rename[stmtname])] + [
                self._transform(subsmtlib) for subsmtlib in smtlib[1:]
            ]
        elif len(smtlib) > 1:
            return [smtlib[0]] + [
                self._transform(subsmtlib) for subsmtlib in smtlib[1:]
            ]
        return smtlib

    @staticmethod
    def _coneOfInfluence(asserts, query):
        cone = []
        cone_vars = set(query.getVars())
        ws = [a for a in asserts if len(set(a.getVars()) & cone_vars) > 0]
        remaining = [a for a in asserts if a not in ws]
        while len(ws) > 0:
            a = ws.pop()
            a_vars = set(a.getVars())
            cone_vars = cone_vars.union(a_vars)
            cone.append(a)
            new_ws = [
                a for a in remaining if len(set(a.getVars()) & cone_vars) > 0
            ]
            remaining = [a for a in remaining if a not in new_ws]
            ws = ws + new_ws
        return cone
Exemple #14
0
def get_controller_cvc4(Theta, initial_size, A, B, u_dim, u_poly, target,
                        avoid_list, avoid_list_dynamic, safe, num_steps,
                        Q_multiplier):
    #set safe to be None if you want to run the avoid_list version. Else set avoid_list to be None

    P, radius_dim, _, lam, G = get_overapproximate_rectangles(
        A, B, Q_multiplier, num_steps)
    radius_list = radius_without_r0(P, radius_dim, num_steps, lam)
    K = G * (-1)

    x_dim = len(radius_list[0])
    sqrt_dim_inverse = 10000.0 / (math.floor(math.sqrt(x_dim * 100000000.0)))

    em = ExprManager()
    s = SmtEngine(em)
    s.setOption("produce-models", SExpr("true"))
    real_type = em.realType()

    x = [[
        em.mkVar("x_ref_%s[%s]" % (i, j + 1), real_type) for j in range(x_dim)
    ] for i in range(num_steps + 1)]
    u = [[
        em.mkVar("u_ref_%s[%s]" % (i, j + 1), real_type) for j in range(u_dim)
    ] for i in range(num_steps)]
    r = em.mkVar("r0", real_type)
    initial_rectangle = []
    for i in range(x_dim):
        rl_mult_r = em.mkExpr(CVC4.MULT, get_cvc4_const(em, radius_list[0][i]),
                              r)
        lo = em.mkExpr(CVC4.MINUS, x[0][i], rl_mult_r)
        hi = em.mkExpr(CVC4.PLUS, x[0][i], rl_mult_r)
        initial_rectangle.append((lo, hi))

    if print_detail:
        print("Adding constraints ... ")
    if safe is None:
        add_constraints(s, em, x, u, r, Theta, radius_list, x_dim, A, u_dim, B,
                        u_poly, target, avoid_list, avoid_list_dynamic,
                        initial_rectangle, num_steps)
    else:
        add_constraints_safety(s, em, x, u, r, Theta, radius_list, x_dim, A,
                               u_dim, B, u_poly, target, safe,
                               initial_rectangle, num_steps)

    if print_detail:
        print("Done adding main constraints ... ")

    first_trajectory_found = False
    s.push()
    if print_detail:
        print("Now adding Theta constraints ... ")
    add_Theta_constraint(s, em, Theta, x[0], True)
    s.push()
    if print_detail:
        print("Done adding Theta constraints ... ")
        print("Now adding radius constraints ... ")
    add_radius_constraint(s, em, r, get_cvc4_const(em, initial_size))

    if print_detail:
        print("Done adding radius constraints ... ")

    Theta_has_been_covered = False
    number_of_steps_initial_size_has_been_halved = 0
    num_iters = 0
    covered_list = []
    trajectory_radius_controller_list = [
    ]  #List of tuples of the form (trajectory, radius_list)

    if print_detail:
        print("Starting iterations")

    while ((not Theta_has_been_covered) and
           number_of_steps_initial_size_has_been_halved < max_decrease_steps
           and num_iters < max_num_iters):
        num_iters = num_iters + 1

        s_check = s.checkSat()
        if print_detail:
            print("checked")
        if (s_check.isSat() == 1):
            # trajectory_radius_controller_list = [[]]
            trajectory = [[
                s.getValue(x[i][j]).getConstRational().getDouble()
                for j in range(x_dim)
            ] for i in range(num_steps + 1)]
            controller = [[
                s.getValue(u[i][j]).getConstRational().getDouble()
                for j in range(u_dim)
            ] for i in range(num_steps)]

            rad = s.getValue(r).getConstRational().getDouble()
            init_point = trajectory[0]
            init_radius = [
                r_i * rad * sqrt_dim_inverse for r_i in radius_list[0]
            ]
            cover = []
            for i in range(len(init_point)):
                x_i = init_point[i]
                r_i = init_radius[i]
                cover.append((x_i - r_i, x_i + r_i))
            covered_list.append((True, cover))
            Theta_has_been_covered = check_covered(x_dim, Theta, covered_list)
            trajectory_radius_controller_list.append(
                (trajectory, [[rad * rad_dim for rad_dim in rad_step]
                              for rad_step in radius_list], controller))

            if print_detail:
                print("Found trajectory from:", trajectory[0],
                      "with radius = ", init_radius[0])

            if not first_trajectory_found:
                first_trajectory_found = True
                s.pop()
                s.pop()
                add_Theta_constraint(s, em, Theta, x[0], False)
            else:
                s.pop()

            add_cover_constraint(s, em, (True, cover), x[0], initial_rectangle)
            s.push()
            add_radius_constraint(s, em, r, get_cvc4_const(em, initial_size))

        else:
            if print_detail:
                print("Fails for:", initial_size)
            initial_size = initial_size * multiplicative_factor_for_radius
            number_of_steps_initial_size_has_been_halved = number_of_steps_initial_size_has_been_halved + 1
            s.pop()
            s.push()
            add_radius_constraint(s, em, r, get_cvc4_const(em, initial_size))

    print("Number of iterations: " + str(num_iters))
    return (K, trajectory_radius_controller_list, covered_list, num_iters)
Exemple #15
0
class CVCWrapper(object):
    options = {
        'produce-models': 'true',
        # Enable experimental string support
        'strings-exp': 'true',
        # Enable modular arithmetic with constant modulus
        'rewrite-divk': 'true',
        # Per Query timeout of 5 seconds
        'tlimit-per': 5000,
        'output-language': 'smt2',
        'input-language': 'smt2'
    }
    logic = 'ALL_SUPPORTED'

    def __init__(self):
        self.asserts = None
        self.query = None
        self.em = None
        self.solver = None

    def findCounterexample(self, asserts, query):
        """Tries to find a counterexample to the query while
           asserts remains valid."""
        self.em = ExprManager()
        self.solver = SmtEngine(self.em)
        for name, value in CVCWrapper.options.items():
            self.solver.setOption(name, SExpr(str(value)))
        self.solver.setLogic(CVCWrapper.logic)
        self.query = query
        self.asserts = self._coneOfInfluence(asserts, query)
        result = self._findModel()
        log.debug("Query -- %s" % self.query)
        log.debug("Asserts -- %s" % asserts)
        log.debug("Cone -- %s" % self.asserts)
        log.debug("Result -- %s" % result)
        return result

    def _findModel(self):
        self.solver.push()
        exprbuilder = ExprBuilder(self.asserts, self.query, self.solver)
        self.solver.assertFormula(exprbuilder.query.cvc_expr)
        try:
            result = self.solver.checkSat()
            log.debug("Solver returned %s" % result.toString())
            if not result.isSat():
                ret = None
            elif result.isUnknown():
                ret = None
            elif result.isSat():
                ret = self._getModel(exprbuilder.cvc_vars)
            else:
                raise Exception("Unexpected SMT result")
        except RuntimeError as r:
            log.debug("CVC exception %s" % r)
            ret = None
        self.solver.pop()
        return ret

    @staticmethod
    def _getModel(variables):
        """Retrieve the model generated for the path expression."""
        return {
            name: cvc_var.getvalue()
            for (name, cvc_var) in variables.items()
        }

    @staticmethod
    def _coneOfInfluence(asserts, query):
        cone = []
        cone_vars = set(query.getVars())
        ws = [a for a in asserts if len(set(a.getVars()) & cone_vars) > 0]
        remaining = [a for a in asserts if a not in ws]
        while len(ws) > 0:
            a = ws.pop()
            a_vars = set(a.getVars())
            cone_vars = cone_vars.union(a_vars)
            cone.append(a)
            new_ws = [
                a for a in remaining if len(set(a.getVars()) & cone_vars) > 0
            ]
            remaining = [a for a in remaining if a not in new_ws]
            ws = ws + new_ws
        return cone
Exemple #16
0
class CVCWrapper(object):
    def __init__(self):
        self.asserts = None
        self.query = None
        self.em = None
        self.solver = None

    def findCounterexample(self, asserts, query):
        """Tries to find a counterexample to the query while
           asserts remains valid."""
        self.em = ExprManager()
        self.solver = SmtEngine(self.em)
        self.solver.setOption("produce-models", SExpr("true"))
        self.solver.setOption("strings-exp", SExpr("true")) # Enable experimental string support
        self.solver.setOption("rewrite-divk", SExpr("true")) # Enable modular arithmetic with constant modulus
        self.solver.setOption("tlimit-per", SExpr("5000")) # Per Query timeout of 5 seconds
        self.solver.setLogic("ALL_SUPPORTED")
        self.query = query
        self.asserts = self._coneOfInfluence(asserts, query)
        result = self._findModel()
        log.debug("Query -- %s" % self.query)
        log.debug("Asserts -- %s" % asserts)
        log.debug("Cone -- %s" % self.asserts)
        log.debug("Result -- %s" % result)
        return result

    def _findModel(self):
        self.solver.push()
        exprbuilder = ExprBuilder(self.asserts, self.query, self.solver)
        try:
            result = self.solver.checkSat()
            log.debug("Solver returned %s" % result.toString())
            if not result.isSat():
                ret = None
            elif result.isUnknown():
                ret = None
            elif result.isSat():
                ret = self._getModel(exprbuilder.cvc_vars)
            else:
                raise Exception("Unexpected SMT result")
        except RuntimeError as r:
            log.debug("CVC exception %s" % r)
            ret = None
        self.solver.pop()
        return ret

    @staticmethod
    def _getModel(variables):
        """Retrieve the model generated for the path expression."""
        return {name: cvc_var.getvalue() for (name, cvc_var) in variables.items()}
	
    @staticmethod
    def _coneOfInfluence(asserts, query):
        cone = []
        cone_vars = set(query.getVars())
        ws = [a for a in asserts if len(set(a.getVars()) & cone_vars) > 0]
        remaining = [a for a in asserts if a not in ws]
        while len(ws) > 0:
            a = ws.pop()
            a_vars = set(a.getVars())
            cone_vars = cone_vars.union(a_vars)
            cone.append(a)
            new_ws = [a for a in remaining if len(set(a.getVars()) & cone_vars) > 0]
            remaining = [a for a in remaining if a not in new_ws]
            ws = ws + new_ws
        return cone
Exemple #17
0
class CVCWrapper(object):
    options = {'produce-models': 'true',
               # Enable experimental string support
               'strings-exp': 'true',
               # Enable modular arithmetic with constant modulus
               'rewrite-divk': 'true',
               'output-language': 'smt2',
               'input-language': 'smt2'}
    logic = 'ALL_SUPPORTED'

    def __init__(self, query_store=None):
        self.asserts = None
        self.query = None
        self.em = None
        self.solver = None
        self.query_store = query_store
        self.smtlib = None

    def findCounterexample(self, asserts, query, timeout=None):
        """Tries to find a counterexample to the query while
           asserts remains valid."""
        startime = time.process_time()
        self.em = ExprManager()
        self.solver = SmtEngine(self.em)
        if timeout is not None:
            self.options['tlimit-per'] = timeout*1000
        for name, value in CVCWrapper.options.items():
            self.solver.setOption(name, SExpr(str(value)))
        self.solver.setLogic(CVCWrapper.logic)
        self.query = query
        self.asserts = asserts
        result, model = self._findModel()
        endtime = time.process_time()
        log.debug("Timeout -- %s" % timeout)
        log.debug("Result -- %s" % result)
        log.debug("Model -- %s" % model)
        log.debug("Solver time: {0:.2f} seconds".format(endtime - startime))
        solvertime = endtime - startime
        return result, model, solvertime

    def _findModel(self):
        self.solver.push()
        exprbuilder = ExprBuilder(self.asserts, self.query, self.solver)
        self.solver.assertFormula(exprbuilder.query.cvc_expr)
        if self.query_store is not None:
            self.smtlib = self._serialize(exprbuilder.query, exprbuilder.cvc_vars)
            self._savequery()
        model = None
        try:
            result = self.solver.checkSat()
            if not result.isSat():
                ret = "UNSAT"
            elif result.isUnknown():
                ret = "UNKNOWN"
            elif result.isSat():
                ret = "SAT"
                model = self._getModel(exprbuilder.cvc_vars)
            else:
                raise Exception("Unexpected SMT result")
        except RuntimeError as r:
            log.debug("CVC exception %s" % r)
            ret = "UNKNOWN"
        except TypeError as t:
            log.error("CVC exception %s" % t)
            ret = "UNKNOWN"
        self.solver.pop()
        return ret, model

    def _savequery(self):
        if not path.isdir(self.query_store):
            raise IOError("Query folder {} not found".format(self.query_store))
        smthash = sha224(bytes(str(self.query), 'UTF-8')).hexdigest()
        filename = path.join(self.query_store, "{}.smt2".format(smthash))
        log.debug('Writing query to {}'.format(filename))
        with open(filename, 'w') as f:
            f.write(self.smtlib)

    @staticmethod
    def _serialize(query, variables):
        smtlib_template = Template("""
(set-logic $logic)
(set-option :strings-exp ${strings_exp})
(set-option :produce-models ${produce_models})
(set-option :rewrite-divk ${rewrite_divk})

$declarevars

(assert $query)

(check-sat)

$getvars
""")
        assignments = {name.replace('-', '_'): value for name, value in CVCWrapper.options.items()}
        assignments['logic'] = CVCWrapper.logic
        assignments['query'] = query
        assignments['declarevars'] = "\n".join(
            "(declare-fun {} () {})".format(name, var.CVC_TYPE) for name, var in variables.items())
        assignments['getvars'] = "\n".join("(get-value ({}))".format(name) for name in variables)
        return smtlib_template.substitute(assignments).strip()

    @staticmethod
    def _getModel(variables):
        """Retrieve the model generated for the path expression."""
        return {name: cvc_var.getvalue() for (name, cvc_var) in variables.items()}
Exemple #18
0
    def __compute_models(self,
                         model,
                         num,
                         blocking_manager,
                         constraints=None,
                         shared_objects=None):
        opts = Options()
        opts.setInputLanguage(CVC4.INPUT_LANG_CVC4)

        exit_with_unknown = False

        if shared_objects is None:
            shared_objects = []

        exprmgr = ExprManager(opts)

        smt = SmtEngine(exprmgr)
        smt.setOption("produce-models", SExpr(True))
        smt.setOption("fmf-bound", SExpr(True))
        smt.setOption("macros-quant", SExpr(True))
        smt.setOption("finite-model-find", SExpr(True))
        #        smt.setOption("repeat-simp", SExpr(True))
        #        smt.setOption("check-models", SExpr(True))
        #        smt.setOption("full-saturate-quant", SExpr(True))
        smt.setOption("incremental", SExpr(True))

        ind = 0

        assertions = blocking_manager.compute_from_sharedobjs(shared_objects)
        model = model + assertions

        if constraints:
            model += "\n%s;" % (constraints)

        parserbuilder = ParserBuilder(exprmgr, "", opts)
        parserbuilder.withStringInput(model)
        parser = parserbuilder.build()

        symboltable = parser.getSymbolTable()

        blocking_manager.exprmgr = exprmgr
        blocking_manager.symboltable = symboltable

        while True:
            cmd = parser.nextCommand()
            if not cmd: break
            cmd.invoke(smt)

        while True:
            checksat = CheckSatCommand()
            checksat.invoke(smt)

            sat = checksat.getResult().isSat() == 1
            unk = checksat.getResult().isUnknown()
            uns = (not sat) and (not unk)

            Logger.log("sat: %s, uns: %s, unk: %s" % (sat, uns, unk), 2)

            exitcond = (not sat) if exit_with_unknown else uns

            if exitcond:
                return (shared_objects, 0)

            (bclauses, shared_obj) = blocking_manager.compute_from_smt(smt)

            Logger.log("%s" % str(shared_obj), 2)

            if shared_obj not in shared_objects:
                shared_objects.append(shared_obj)
            else:
                if constraints is not None:
                    return (shared_objects, 2)

            for bclause in bclauses:
                assertion = AssertCommand(bclause)
                assertion.invoke(smt)

            Logger.msg(".", 0, constraints is None, 0)

            ind += 1
            if (num != -1) and (ind >= num):
                return (shared_objects, 1)

        return (None, -1)